比较R中的单列中的字符

  • 本文关键字:单列中 字符 比较 r
  • 更新时间 :
  • 英文 :

head(df)
   V1          V2 V3 V4 V5 V6  V7  V8  V9  V10 V11
1 1152652 1152652  0  0  2 -9 1 1 2 2 0 0 2 2 1 1
2 1051495 1051495  0  0  2 -9 1 1 2 2 0 0 2 2 1 1
3 1195877 1195877  0  0  2 -9 1 1 2 2 0 0 2 2 1 1

此DF约为200,000行。我想比较第八列中的两个整数。我尝试转换。当我使用strsplit()时,情况变得非常混乱。

,例如,如果我服用V8列:

V8 <- as.character(df$V8)
test <- strsplit(V8, " ")
head(test)
[[1]]
[1] "2" "2"

是否有更优雅的人想这样做?我只对第八列感兴趣。非常感谢。

使用tidyr::separate,您可以将V8列分为两个列(即V8aV8b):

library(tidyr)
df <- separate(df,V8,c("V8a","V8b"))
       V1      V2 V3 V4 V5 V6  V7 V8a V8b  V9 V10 V11
1 1152652 1152652  0  0  2 -9 1 1   2   2 0 0 2 2 1 1
2 1051495 1051495  0  0  2 -9 1 1   2   2 0 0 2 2 1 1
3 1195877 1195877  0  0  2 -9 1 1   2   2 0 0 2 2 1 1

然后,您可以比较以下内容:

is_eq <- df$V8a == df$V8b
##[1] TRUE TRUE TRUE

数据:

df <- structure(list(V1 = c(1152652L, 1051495L, 1195877L), V2 = c(1152652L, 
1051495L, 1195877L), V3 = c(0L, 0L, 0L), V4 = c(0L, 0L, 0L), 
    V5 = c(2L, 2L, 2L), V6 = c(-9L, -9L, -9L), V7 = c("1 1", 
    "1 1", "1 1"), V8 = c("2 2", "2 2", "2 2"), V9 = c("0 0", 
    "0 0", "0 0"), V10 = c("2 2", "2 2", "2 2"), V11 = c("1 1", 
    "1 1", "1 1")), .Names = c("V1", "V2", "V3", "V4", "V5", 
"V6", "V7", "V8", "V9", "V10", "V11"), class = "data.frame", row.names = c(NA, 
-3L))
##       V1      V2 V3 V4 V5 V6  V7  V8  V9 V10 V11
##1 1152652 1152652  0  0  2 -9 1 1 2 2 0 0 2 2 1 1
##2 1051495 1051495  0  0  2 -9 1 1 2 2 0 0 2 2 1 1
##3 1195877 1195877  0  0  2 -9 1 1 2 2 0 0 2 2 1 1

我想留下一个想法,您可以为多列处理此任务,因为数据集包含几列,分别包含两个数字。我在下面创建了一个简单的数据。在这里,V1和V2包含两个数字。因此,我想对这些列进行数字比较。第一步是确定哪些列包含两个数字。它们之间应该有一个空间。使用此想法,您可以识别目标列。在grep()中,我选择了数据的第一行,并搜索了包含一个空间的字符串。然后,我拿起列名称(即V1和V2)。第二步是用cSplit()拆分目标列。一旦拆分列,数字变为数字,而不是字符。在第三步中,您选择lapply()中的一对列,然后进行简单的计算。如果两个数字相同,则减去应返回0。您可以将其用于逻辑检查并创建一个名为check的新列,并且仅选择列。然后,您可以使用cbind()创建一个数据表。最后,您需要使用ind(即V1和V2)更新列名。

library(dplyr)
library(data.table)
library(splitstackshape)
mydf <- data.frame(V1 = c("1 1", "2 3", "3 3"),
                   V2 = c("10 11", "12 12", "13 13"),
                   V3 = 101:103,
                   stringsAsFactors = FALSE)
#   V1    V2  V3
#1 1 1 10 11 101
#2 2 3 12 12 102
#3 3 3 13 13 103
# Find columns which include two numbers.
mydf[, grepl(pattern = "\s", x = mydf[1, ])] %>%
colnames -> ind
# Prepare a data set splitting numbers in one column
cSplit(mydf, splitCols = ind, direction = "wide", sep = " ") -> temp
# Choose a pair of columns. Check if the subtraction generates 0.
# If 0, two numbers are identical. If not, they do not match.
lapply(ind, function(i){
    temp[, grep(i, x = names(temp)), with = FALSE] -> foo
    foo[, check  :=  foo[, 1, with = FALSE]- foo[, 2, with = FALSE] == 0]
    foo[, 3, with = FALSE] -> foo
    foo
   }) -> temp
# Create a data table
do.call(cbind, temp) -> out
# Update column names
setnames(out, ind) 
#      V1    V2
#1:  TRUE FALSE
#2: FALSE  TRUE
#3:  TRUE  TRUE

最新更新