簡體   English   中英

將矢量的數字列表與矢量的字符列表相匹配

[英]matching a numeric list of vectors to a character list of vectors

我有一個字符串列表(向量),我有一個數字向量列表,我想用它來查找第一個單詞。 我將它安排為下面的數據表,以幫助您可視化:

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

我想從第一行的字符串中提取第2和第8個單詞,然后從第2行的字符串中提取第1個和第4個單詞,如下面的MATCH列所示:

                                 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

復制兩個列表的代碼:

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()和其他各種組合,但是很快就會出現。

我很欣賞實現這一目標的最有效方法。

我剛才意識到mapply就是答案:

SEL<-function(x, y)x[y]
mapply(SEL, x$words, neg2, SIMPLIFY = FALSE)
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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM