类似于 R 中的 Countifs 和 Sumifs
Similar to Countifs and Sumifs in R
我应该先说明一下...我不能使用 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
到 filter
具有 'P1' 值等于 'P2' 的行,然后 summarise
'count_of_friends' 通过取sum
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
我应该先说明一下...我不能使用 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
到 filter
具有 'P1' 值等于 'P2' 的行,然后 summarise
'count_of_friends' 通过取sum
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