【发布时间】:2018-12-11 17:27:12
【问题描述】:
这个问题是counting specific words across multiple columns in R 的修改版本,但增加了为某些列赋予不同权重的复杂性。如何使某些列计为 1,而其他列计为 0.5?
可重现的例子:
df <- data.frame(id=c(1, 2, 3, 4, 5), staple_1=c("potato", "potato","rice","fruit","coffee"),
staple2_half1=c("yams","beer","potato","rice","yams"),
staple2_half2=c("potato","rice","yams","rice","yams"),
staple_3=c("rice","peanuts","fruit","fruit","rice"))
potato<-c("potato")
yams<-c("yams")
staples<-c("potato","cassava","rice","yams")
给予:
id staple_1 staple2_half1 staple2_half2 staple_3
1 potato yams potato rice
2 potato beer rice peanuts
3 rice potato yams fruit
4 fruit rice rice fruit
5 coffee yams yams rice
现在我想创建 2 个附加列来汇总“土豆”和“山药”的计数,但通过修改以下代码,使“半”列(staple2_half1 和staple2_half2)中的任何计数仅计为 0.5 而不是1.
使用原始答案的结果不正确:
df$staples <- apply(df, 1, function(x) sum(staples %in% x))
df$potato<- apply(df, 1, function(x) sum(potato %in% x))
df$yams<- apply(df, 1, function(x) sum(yams %in% x))
给予:
id staple_1 staple2_half1 staple2_half2 staple_3 staples potato yams
1 potato yams potato rice 3 1 1
2 potato beer rice peanuts 2 1 0
3 rice potato yams fruit 3 1 1
4 fruit rice rice fruit 1 0 0
5 coffee yams yams rice 2 0 1
基于加权计数的期望结果:
id staple_1 staple2_half1 staple2_half2 staple_3 staples potato yams
1 potato yams potato rice 3 1.5 0.5
2 potato beer rice peanuts 1.5 1 0
3 rice potato yams fruit 2 0.5 0.5
4 fruit rice rice fruit 1 0 0
5 coffee yams yams rice 2 0 1
【问题讨论】:
标签: r