【发布时间】:2019-07-02 03:04:21
【问题描述】:
我需要一些帮助。
假设我有这个:
# A tibble: 10 x 3
a b c
<chr> <dbl> <lgl>
1 a 1 TRUE
2 a 1 TRUE
3 a 1 TRUE
4 a 2 TRUE
5 a 2 TRUE
6 a 2 FALSE
7 a 2 FALSE
8 a 3 FALSE
9 a 3 FALSE
10 a 3 FALSE
structure(list(a = c("a", "a", "a", "a", "a", "a", "a", "a",
"a", "a"), b = c(1, 1, 1, 2, 2, 2, 2, 3, 3, 3), c = c(TRUE, TRUE,
TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE)), row.names = c(NA,
-10L), class = c("tbl_df", "tbl", "data.frame"))
我想group_by 列b 并在每个组内计算T == TRUE 在列c 中的相对频率以生成列d。
所以我想要这个输出:
# A tibble: 10 x 4
a b c d
<chr> <dbl> <lgl> <dbl>
1 a 1 TRUE 1
2 a 1 TRUE 1
3 a 1 TRUE 1
4 a 2 TRUE 0.5
5 a 2 TRUE 0.5
6 a 2 FALSE 0.5
7 a 2 FALSE 0.5
8 a 3 FALSE 0
9 a 3 FALSE 0
10 a 3 FALSE 0
structure(list(a = c("a", "a", "a", "a", "a", "a", "a", "a",
"a", "a"), b = c(1, 1, 1, 2, 2, 2, 2, 3, 3, 3), c = c(TRUE, TRUE,
TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE), d = c(1,
1, 1, 0.5, 0.5, 0.5, 0.5, 0, 0, 0)), row.names = c(NA, -10L), class = c("tbl_df",
"tbl", "data.frame"))
最好使用dplyr 或tidyverse。
我试过了:
#1
t %>%
group_by(b) %>%
mutate(
d = nrow(c[c == T])/nrow()
)
#2
t %>%
group_by(b) %>%
mutate(
d = count(c[c == T])/count()
)
#3
t %>%
group_by(b) %>%
mutate(
d = nrow(any(c[c == T]))/nrow(any())
)
两者都不起作用。
类似的问题(但不同):
How to calculate the relative frequency per groups
R: relative frequency in r by factor
任何帮助表示赞赏。
提前致谢。
【问题讨论】:
-
在我看来,这个问题是那些“类似问题”(可能还有其他问题)的副本。不知道为什么重新打开。
-
@neifws OP在帖子中已经提到这不是他的观点
Similar questions (but different):的欺骗@ -
@neilfws 我打开它是因为我认为它是一个新问题或更具体的问题,因为我无法使用任何其他问题来解决我的问题。