2011-11-27 92 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

感謝您的幫助。這個例子很小,索引是有意義的,但我正在處理大量的文本,其中'手'索引是不合適的。 –