我有一个data.frame
,看起来像这样:
V1 V2 V3
1 143 143 143
2 141 141 143
3 195 195 141
4 121 121 121
5 142 142 142
我想使用rowSums
来计算一组值在一行中出现的次数,例如值c(141, 143)
,因此答案将逐行计算该向量中值的出现次数:
3, 3, 1, 0, 0
好奇为什么%in%
的这种方法没有像预期的那样工作:
rowSums(df[df %in% c(141, 143)], na.rm = T))
谢谢!
尝试这种apply()
方法:
#Code
apply(df,1,function(x) sum(x %in% c(141, 143)))
输出:
1 2 3 4 5
3 3 1 0 0
使用的一些数据:
#Data
df <- structure(list(V1 = c(143L, 141L, 195L, 121L, 142L), V2 = c(143L,
141L, 195L, 121L, 142L), V3 = c(143L, 143L, 141L, 121L, 142L)), class = "data.frame", row.names = c("1",
"2", "3", "4", "5"))
如果df %in% c(141, 143)
。。。并考虑data.frame实际上是一个列表。
这里有一个替代方案:
rowSums(df == 141 | df == 143)
在sapply
中可能更快。
rowSums(sapply(dat, `%in%`, c(141, 143)))
# [1] 3 3 1 0 0
甚至更快(尽管看起来很奇怪(。
rowSums(t(do.call(rbind, lapply(dat, `%in%`, c(141, 143)))))
# [1] 3 3 1 0 0
基准:
Unit: microseconds
expr min lq mean median uq max neval cld
rowSums(dat == 141 | dat == 143) 143.643 147.8535 155.86417 151.807 158.6965 227.584 100 b
rowSums(sapply(dat, `%in%`, c(141, 143))) 52.048 54.0900 58.10532 55.365 56.7685 181.658 100 a
rowSums(t(do.call(rbind, lapply(dat, `%in%`, c(141, 143))))) 37.505 39.8015 42.94497 41.077 42.2255 144.663 100 a
apply(dat, 1, function(x) sum(x %in% c(141, 143))) 149.256 153.5940 183.03378 155.890 160.2270 2560.057 100 b
数据:
dat <- structure(list(V1 = c(143L, 141L, 195L, 121L, 142L), V2 = c(143L,
141L, 195L, 121L, 142L), V3 = c(143L, 143L, 141L, 121L, 142L)), class = "data.frame", row.names = c("1",
"2", "3", "4", "5"))
带有rowwise/c_across
的选项
library(dplyr)
df %>%
rowwise %>%
mutate(Sum = sum(c_across(everything()) %in% c(141, 143)))
# A tibble: 5 x 4
# Rowwise:
# V1 V2 V3 Sum
# <int> <int> <int> <int>
#1 143 143 143 3
#2 141 141 143 3
#3 195 195 141 1
#4 121 121 121 0
#5 142 142 142 0
数据
df <- structure(list(V1 = c(143L, 141L, 195L, 121L, 142L), V2 = c(143L,
141L, 195L, 121L, 142L), V3 = c(143L, 143L, 141L, 121L, 142L)),
class = "data.frame", row.names = c("1",
"2", "3", "4", "5"))