每列 R 中特定值的次数
number of times specific value in each column R
我有:
library(tidyverse)
df <- tibble(one=c(1,1,1,2,2,2,3,3),
log1 = c(TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE),
log2 = c(TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE),
log3 = c(TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE))
我想找出单词“FALSE”在每个列和组中出现的次数,并且 return a df
我试过map_df(df, function(x) sum(x==FALSE))
和
df %>%
group_by(one) %>%
map_df( function(x) sum(x==FALSE))
但他们没有分成不同的组。
这也会出错
df %>%
group_by(one) %>%
summarise( function(x) sum(x==FALSE))
有什么建议吗?
您可以使用 across
处理多个列
library(dplyr)
df %>%
group_by(one) %>%
summarise(across(starts_with("log"), function(x) sum(x==F)))
# A tibble: 3 × 4
one log1 log2 log3
<dbl> <int> <int> <int>
1 1 1 1 1
2 2 3 3 3
3 3 0 2 1
按照@RuiBarradas
所述,直接使用布尔值是处理逻辑的一种不错且更短的方法
...
summarise(across(starts_with("log"), function(x) sum(!x)))
...
我有:
library(tidyverse)
df <- tibble(one=c(1,1,1,2,2,2,3,3),
log1 = c(TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE),
log2 = c(TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE),
log3 = c(TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE))
我想找出单词“FALSE”在每个列和组中出现的次数,并且 return a df
我试过map_df(df, function(x) sum(x==FALSE))
和
df %>%
group_by(one) %>%
map_df( function(x) sum(x==FALSE))
但他们没有分成不同的组。
这也会出错
df %>%
group_by(one) %>%
summarise( function(x) sum(x==FALSE))
有什么建议吗?
您可以使用 across
处理多个列
library(dplyr)
df %>%
group_by(one) %>%
summarise(across(starts_with("log"), function(x) sum(x==F)))
# A tibble: 3 × 4
one log1 log2 log3
<dbl> <int> <int> <int>
1 1 1 1 1
2 2 3 3 3
3 3 0 2 1
按照@RuiBarradas
所述,直接使用布尔值是处理逻辑的一种不错且更短的方法...
summarise(across(starts_with("log"), function(x) sum(!x)))
...