我应该在此前言...我不能使用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中怎么做?
答案 0 :(得分:0)
以下是基础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")