r - 在对它们执行转换时跨列求和
问题描述
假设我有以下数据集
test_df = game_df = read.table(text = "a_bias b_bias c_bias d_bias
dog dog cat cat
NA NA NA NA
cat cat cat cat
dog NA dog dog", header = T)
我想创建一个名为的新列,它等于所有以 word 结尾的列中出现dog_sum
的总次数。这是我目前的方法:dog
bias
test_df %>% rowwise() %>%
mutate(dog_sum = sum(across(ends_with("bias"), ~ifelse(. == "dog", 1, 0)), na.rm = T))
问题是当整行包含NAs
. 有没有更好的方法来解决这个问题?
更一般地说,我想为匹配的每一列改变新列,ends_with("bias")
如果包含,则此新列应设置为 1,dog
否则设置为 0。因此,最终结果将是有四个名为a_bias_dog
、b_bias_dog
等的列,如果该特定行存在“dog”,则设置为 1,否则设置为 0。我如何实现这一目标?
解决方案
我们可以rowSums
使用矢量化方法来做到这一点,并且应该比rowwise/sum
library(dplyr)
test_df %>%
mutate(dog_sum = rowSums(across(ends_with('bias')) == 'dog',
na.rm = TRUE))
-输出
a_bias b_bias c_bias d_bias dog_sum
1 dog dog cat cat 2
2 <NA> <NA> <NA> <NA> 0
3 cat cat cat cat 0
4 dog <NA> dog dog 3
如果我们想生成新列,请使用
test_df %>%
mutate(across(ends_with('bias'), ~ +(. %in% 'dog'), .names = "{.col}_dog"))
-输出
a_bias b_bias c_bias d_bias a_bias_dog b_bias_dog c_bias_dog d_bias_dog
1 dog dog cat cat 1 1 0 0
2 <NA> <NA> <NA> <NA> 0 0 0 0
3 cat cat cat cat 0 0 0 0
4 dog <NA> dog dog 1 0 1 1
推荐阅读
- c - macOS 上的 getgroups() 不会返回所有补充组,而是只返回主要组
- docker - docker-compose 变量替换强制变量
- combobox - 不可编辑组合框的 setValue
- java - Firebase 令牌生成器在 APN 中失败
- reactjs - 关闭并重新打开选项卡 IE 11 的网页问题
- python - 从 python 打包的角度来看,“import numpy”或“numpy import functionnames”之间有什么区别吗?
- android - 订阅成功执行后 rxjava 计时器抛出超时异常
- python - 我的程序无法使用 Python 中的 mysql 连接器库在 MySQL 中存储值
- c# - 当一个玩家彼此靠近时,如何降低一个玩家的速度并提高另一个玩家的速度?
- jquery - 选择 SVG 组中的元素