2017-09-27 183 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

相關問題