我应该在此前言...我不能使用dplyr。它只是没有安装在我的R版本中。
我如何在R中执行类似于countifs
或sumifs
函数的操作?
P1 | P2 | Match | Same | count_of_friends
M | F | FALSE | FALSE| 6
M | M | TRUE | TRUE | 7
F | M | FALSE | FALSE| 10
F | F | TRUE | FALSE| 2
我基本上会寻找类似于EXCEL的东西
SUMIFS(Match == Same; count_of_friends)
如果两个人的性别相同,我想找到朋友的总和,如果P1是女性,我想找到朋友数量的总和。
然后我还想知道如何只计算朋友数超过5的实例等。
你怎么在R?
这是基础R中的一种方法:
第一个问题,根据逻辑矢量P1 == P2
对数据帧进行子集化,并对第5列中的值求和
sum(df[with(df, P1 == P2), 5])
#output
9
第二个问题,根据逻辑矢量count_of_friends > 5
对数据帧进行子集化,并检查结果数据帧的行数:
nrow(df[with(df, count_of_friends > 5),])
#output
3
数据:
> dput(df)
structure(list(P1 = structure(c(2L, 2L, 1L, 1L), .Label = c("F",
"M"), class = "factor"), P2 = structure(c(1L, 2L, 2L, 1L), .Label = c("F",
"M"), class = "factor"), Match = c(FALSE, TRUE, FALSE, TRUE),
Same = c(FALSE, TRUE, FALSE, FALSE), count_of_friends = c(6,
7, 10, 2)), .Names = c("P1", "P2", "Match", "Same", "count_of_friends"
), row.names = c(NA, -4L), class = "data.frame")
我们可以将dplyr
用于'P1'值等于'P2'的filter
行,然后使用summarise
将sum
用于'count_of_friends'
library(dplyr)
df %>%
filter(P1 == P2) %>%
summarise(Sum = sum(count_of_friends))
# Sum
#1 9
对于第二部分,我们在'count_of_friends'上做filter
并得到nrow
df %>%
filter(count_of_friends > 5) %>%
nrow
#[1] 3