根据列表提取列

extract columns according to a list

我有一个table df,它列出了1000个文档中2000个词的出现频率

id   happy so  today    cut  song dad  may
 1    2      4     3     2    1    0    2 
 2    1      2     1     4    0    2    2
 3    0      2     1     1    2    0    3

我想根据这样的列表从 table 中提取一些列(单词):

     Topic 1   Topic 2   
[1,] "cut"     "one"     
[2,] "may"     "day"     
[3,] "song"    "job"     
[4,] "act"     "start"   
[5,] "control" "check"

从table中提取一列是df$col,这里df中的列名就是列表中的名字。结果会是这样的:

id    cut  may song 
 1     2     2   1    
 2     4     2   0
 3     1     3   2

我们可以使用match。根据 "m2"

的第一列提取 "df1" 中的列
df1[c(1, match(m2[,"Topic1"], names(df1), nomatch=0))]
#   id cut may song
#1  1   2   2    1
#2  2   4   2    0
#3  3   1   3    2

由于 'm2' 是 matrix,我们也可以在同一步骤中对所有列执行此操作

df1[c(1, match(m2, names(df1), nomatch=0))]

如果我们需要根据 "m2" (matrix) 中的每一列对初始数据集进行子集化,

lapply(seq_len(ncol(m2)), function(i) 
        df1[c(1, match(m2[,i], names(df1), nomatch=0))]
        )
#[[1]]
#  id cut may song
#1  1   2   2    1
#2  2   4   2    0
#3  3   1   3    2

#[[2]]
#  id
#1  1
#2  2
#3  3

注意:在"m2"的第二列中,没有与'df1'的列名匹配的元素。