r - 如何计算跨列字数的加权总和?
问题描述
这个问题是计算 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
解决方案
如果对 的列执行函数apply
,则会得到一个真假值矩阵。然后进行加权求和,您可以将此矩阵乘以权重向量。%in%
df[, -1]
words <- data.frame(staples, potato, yams)
weights <- 1 - 0.5*grepl('half', names(df[, -1]))
df[names(words)] <-
lapply(words, function(x) apply(df[, -1], 2, `%in%`, x) %*% weights)
df
# id staple_1 staple2_half1 staple2_half2 staple_3 staples potato yams
# 1 1 potato yams potato rice 3.0 1.5 0.5
# 2 2 potato beer rice peanuts 1.5 1.0 0.0
# 3 3 rice potato yams fruit 2.0 0.5 0.5
# 4 4 fruit rice rice fruit 1.0 0.0 0.0
# 5 5 coffee yams yams rice 2.0 0.0 1.0
apply(df1[, -1], 2, ...
输出的示例
apply(df[, -1], 2, `%in%`, potato)
# staple_1 staple2_half1 staple2_half2 staple_3
# [1,] TRUE FALSE TRUE FALSE
# [2,] TRUE FALSE FALSE FALSE
# [3,] FALSE TRUE FALSE FALSE
# [4,] FALSE FALSE FALSE FALSE
# [5,] FALSE FALSE FALSE FALSE
apply(df[, -1], 2, `%in%`, potato) %*% weights
# [,1]
# [1,] 1.5
# [2,] 1.0
# [3,] 0.5
# [4,] 0.0
# [5,] 0.0
推荐阅读
- css - 如何将图像导入 CSS 模块?
- c++ - C++ 分离的线程可以通过哪些可能的方式发出它正在终止的信号?
- sip - kamailio:如何在 VIA 标头中发送带有端口号的回复
- python - Python 不区分大小写或敏感字符串作为输入
- javascript - 设置没有百分比缩放的 Path2D 对象的大小
- java - 在 Hibernate 中使用 Spring boot 配置的 Jackson Objectmapper
- ios - 文本字段点击正在关闭 SwiftUI 中的导航链接
- python - 如果日期的时间戳不存在,则添加午夜 00:00:00 时间戳?
- python - 嵌入的 if 语句无法正常工作
- javascript - 检测是否存在 div 的问题 -> Uncaught SyntaxError: Unexpected string