2017-09-27 181 views
0

我使用LDA与主题相关的数据帧terms选择返回值:sapply对数据帧的列使用从另一个数据帧

Topic 1 Topic 2 Topic 3 
foo1  bar1  cow1 
foo2  bar2  cow2 
foo3  bar3  cow3 

在另一个数据帧items,我有一个链接到一个主题的项目清单:

ItemID Topic 
item1  1 
item2  1 
item3  2 
item4  3 

我想创建一个新的列items$terms返回与该主题相关的条款:

ItemID Topic terms 
item1  1  foo1 foo2 foo3 
item2  1  foo1 foo2 foo3 
item3  2  bar1 bar2 bar3 
item4  3  cow1 cow2 cow3 

我尝试这样做:

items$terms <- sapply(items$Topic,paste(terms[,x],collapse = " ")) 

# For each item, find the topic, and return the pasted terms from topicterms 

但我得到的错误:

Error in [.data.frame(topicterms, , x) : object 'x' not found.

你能告诉我什么,我做错了?

+0

什么是'topicterms'?可能你需要'sapply(items $ Topic,function(x)terms [paste(“Topic”,x)])' –

回答

1

你根本忘了sapply需要一个功能,而不是一个表达式作为其参数:

items$terms <- sapply(items$Topic,function(x) paste(topicterms[,x],collapse = " "))

然而,这一提法将需要topicterms列名于items完全匹配的主题值,他们现在不是 - 一个是数字,一个是附加数字的字符串"Topic "。只需更改列名即可:

names(topicterms) <- 1:3

+0

不是topicterms [,3]返回第三列吗? – TMrtSmith

+0

如果我在例如项目$主题[1]它的工作原理 – TMrtSmith

+0

这个工程,但我想知道为什么它没有工作时引用列号而不是列名 – TMrtSmith

相关问题