0

我有两个数据框,第一个 ( dt) 包含所有数据框,chr第二个 ( TargetWord) 也是包含的字典chr。我曾经pmatch在 中搜索dt可用的单词TargetWord并从 中返回位置TargetWord。当数据框很小时,它工作正常。但是当数据帧很大时问题就开始了,它只返回第一列的单词位置,其余的列都变成了 NA

## Data Table
word_1 <- c("conflict","", "resolved", "", "", "")
word_2 <- c("", "one", "tricky", "one", "", "one")
word_3 <- c("thanks","", "", "comments", "par","")
word_4 <- c("thanks","", "", "comments", "par","")
word_5 <- c("", "one", "tricky", "one", "", "one")
dt <- data.frame(word_1, word_2, word_3,word_4, word_5, stringsAsFactors = FALSE)

## Targeted Words
TargetWord <- data.frame(cbind(c("conflict", "thanks", "tricky", "one", "two", "three")))

## convert into matrix (needed)
dt <- as.matrix(dt)
TargetWord <- as.matrix(TargetWord)

result <- `dim<-`(pmatch(dt, TargetWord, duplicates.ok=TRUE), dim(dt))
print(result)

返回结果,

     [,1] [,2] [,3] [,4] [,5]
[1,]    1   NA    2    2   NA
[2,]   NA    4   NA   NA    4
[3,]   NA    3   NA   NA    3
[4,]   NA    4   NA   NA    4
[5,]   NA   NA   NA   NA   NA
[6,]   NA    4   NA   NA    4

现在在阅读.csv下面的两个之后,结果只是第一列,我希望它用于所有列,如上面的结果。Bellow,dt1 = 79*50 数据帧,word_dict 13901*1 数据帧。

#################### on big data #####################################
dt1 <- read.csv("C:/Users/Wonderland/Downloads/string_feature.csv", stringsAsFactors = FALSE)
word_dict <- read.csv("C:/Users/Wonderland/Downloads/word_dict.csv", stringsAsFactors = FALSE)

dt1 <- as.matrix(dt1)
word_dict <- as.matrix(word_dict)

result <- `dim<-`(pmatch(dt1, word_dict, duplicates.ok=TRUE), dim(dt1))
print(result)
4

1 回答 1

0

尝试应用:

apply(dt,2,function(x) pmatch(x,TargetWord,duplicates.ok = T))

如您所见,结果是相同的,但它可能适用于巨大的数据框

     word_1 word_2 word_3 word_4 word_5
[1,]      1     NA      2      2     NA
[2,]     NA      4     NA     NA      4
[3,]     NA      3     NA     NA      3
[4,]     NA     NA     NA     NA     NA
[5,]     NA     NA     NA     NA     NA
[6,]     NA     NA     NA     NA     NA

我试过:

word_1 <- rep(c("conflict","", "resolved", "", "", ""),1000)
word_2 <- rep(c("", "one", "tricky", "one", "", "one"),1000)
word_3 <- rep(c("thanks","", "", "comments", "par",""),1000)
word_4 <- rep(c("thanks","", "", "comments", "par",""),1000)
word_5 <- rep(c("", "one", "tricky", "one", "", "one"),1000)

使用所有相同的代码并且它有效。

于 2017-03-29T02:01:34.803 回答