使用 dplyr 获取多列值的频率?
Get frequency of values for multiple columns using dplyr?
我有一个如下所示的数据框:
a b c d e
1 0 0 1 1
.5 1 1 0 1
1 1. .5 .5. 0
0 0 1 NA 1
0 1 0 1 .5
我正在寻找类似这样的输出:
col val count
a 1 2
.5 1
0 2
b 1 3
0 2
c 1 2
.5 1
0 2
d 1 2
.5 1
0 1
NA 1
e 1 3
.5 1
0 1
我试过使用
data %>%
summarize_at(colnames(data)), n(), na.rm = TRUE)
但这并没有给我我想要的。非常感谢任何建议,谢谢!
我假设第 d 列第 3 行有错字,.5。确实是 0.5,在这种情况下,您可以执行以下操作:
library(tidyr)
library(dplyr)
df %>%
pivot_longer(everything()) %>%
group_by(name, value) %>%
summarise(count = n()) %>%
arrange(name, desc(value))
# or more succinctly as pointed out by @LMc
df %>%
pivot_longer(everything()) %>%
count(name, value) %>%
arrange(name, desc(value))
#> # A tibble: 15 x 3
#> name value count
#> <chr> <dbl> <int>
#> 1 a 1 2
#> 2 a 0.5 1
#> 3 a 0 2
#> 4 b 1 3
#> 5 b 0 2
#> 6 c 1 2
#> 7 c 0.5 1
#> 8 c 0 2
#> 9 d 1 2
#> 10 d 0.5 1
#> 11 d 0 1
#> 12 d NA 1
#> 13 e 1 3
#> 14 e 0.5 1
#> 15 e 0 1
数据
df <- structure(list(a = c(1, 0.5, 1, 0, 0), b = c(0, 1, 1, 0, 1),
c = c(0, 1, 0.5, 1, 0), d = c(1, 0, 0.5, NA, 1),
e = c(1, 1, 0, 1, 0.5)), class = "data.frame", row.names = c(NA,
-5L))
由 reprex package (v2.0.0)
于 2021-04-13 创建
我有一个如下所示的数据框:
a b c d e
1 0 0 1 1
.5 1 1 0 1
1 1. .5 .5. 0
0 0 1 NA 1
0 1 0 1 .5
我正在寻找类似这样的输出:
col val count
a 1 2
.5 1
0 2
b 1 3
0 2
c 1 2
.5 1
0 2
d 1 2
.5 1
0 1
NA 1
e 1 3
.5 1
0 1
我试过使用
data %>%
summarize_at(colnames(data)), n(), na.rm = TRUE)
但这并没有给我我想要的。非常感谢任何建议,谢谢!
我假设第 d 列第 3 行有错字,.5。确实是 0.5,在这种情况下,您可以执行以下操作:
library(tidyr)
library(dplyr)
df %>%
pivot_longer(everything()) %>%
group_by(name, value) %>%
summarise(count = n()) %>%
arrange(name, desc(value))
# or more succinctly as pointed out by @LMc
df %>%
pivot_longer(everything()) %>%
count(name, value) %>%
arrange(name, desc(value))
#> # A tibble: 15 x 3
#> name value count
#> <chr> <dbl> <int>
#> 1 a 1 2
#> 2 a 0.5 1
#> 3 a 0 2
#> 4 b 1 3
#> 5 b 0 2
#> 6 c 1 2
#> 7 c 0.5 1
#> 8 c 0 2
#> 9 d 1 2
#> 10 d 0.5 1
#> 11 d 0 1
#> 12 d NA 1
#> 13 e 1 3
#> 14 e 0.5 1
#> 15 e 0 1
数据
df <- structure(list(a = c(1, 0.5, 1, 0, 0), b = c(0, 1, 1, 0, 1),
c = c(0, 1, 0.5, 1, 0), d = c(1, 0, 0.5, NA, 1),
e = c(1, 1, 0, 1, 0.5)), class = "data.frame", row.names = c(NA,
-5L))
由 reprex package (v2.0.0)
于 2021-04-13 创建