2011-11-27 43 views
1

我有一个字符串列表(向量),我有一个数字向量列表,我想用它来查找第一个字词。我有如下构成一个数据表,以帮助您可视化:将向量的数值列表与向量的字符列表进行匹配

        words neg2 
1 i, do, not, like, when, she, is, mean 2, 8 
2    i, think, its, not, bad 1, 4 

我想提取从字符串的第2个和第8个字一行,然后将第1和第四个字从字符串的行2如下图所示的匹配列:

        words neg2 MATCH 
1 i, do, not, like, when, she, is, mean 2, 8 do, mean 
2    i, think, its, not, bad 1, 4 i, not 

代码重现2名列表:

neg2<-list(c(2, 8), c(1, 4)) 
x$words <-list(c("i", "do", "not", "like", "when", "she", "is", "mean"), 
    c("i", "think", "its", "not", "bad")) 

我知道这是很容易,我只是没有看到它。我尝试过使用match()和lapply()以及其他各种组合,但是我会尽快完成。

我会很感激最有效的方式来实现这一点。

回答

3

我才意识到mapply是答案:

SEL<-function(x, y)x[y] 
mapply(SEL, x$words, neg2, SIMPLIFY = FALSE) 
+0

'mapply'得不到使用。 +1 –

+0

如果这是答案,您可以将自己的答案标记为正确的答案。 –

0
words <- list(c("i", "do", "not", "like", "when", "she", "is", "mean"), 
    c("i", "think", "its", "not", "bad")) 
neg2<-list(c(2, 8), c(1, 4)) 
words[[1]][neg2[[1]]] 
words[[2]][neg2[[2]]] 

或者,单词和索引的任意长的名单:

words1 <- list() 
for(i in 1:length(words)) { 
    words1[[i]] <- words[[i]][neg2[[i]]] 
} 

看起来像你只需要了解R.名单如何索引见 http://cran.r-project.org/doc/manuals/R-lang.html#Indexing

+0

感谢您的帮助。这个例子很小,索引是有意义的,但我正在处理大量的文本,其中'手'索引是不合适的。 –