获取 R dplyr 中每列中 1 的百分比

  • 本文关键字:百分比 dplyr 获取 r dplyr
  • 更新时间 :
  • 英文 :


我有一个类似这样的DF:

row_id   stn_1 stn_2 stn_3 stn_4 stn_5
1        1     0     1     0     1
2        0     1     0     0     0
3        1     0     0     0     0
4        1     0     1     0     0
5        0     0     0     1     0

我想得到stn在数据中出现的百分比。基本上是除row_id之外的每列中1的百分比。

预期输出:

stn    percentage
stn_1  .60
stn_2  .20
stn_3  .40
stn_4  .20
stn_5  .20

我如何在dplyr中做到这一点?

使用dplyrtidyr,可以进行

dd %>% 
summarize(across(-row_id, mean)) %>% 
pivot_longer(names_to="stn", values_to="percentage", everything())
#   stn   percentage
#   <chr>      <dbl>
# 1 stn_1        0.6
# 2 stn_2        0.2
# 3 stn_3        0.4
# 4 stn_4        0.2
# 5 stn_5        0.2

summarize进行计算,pivot_longer进行整形。

带一点可编程enframecolMeans怎么样?(不是dplyr,但可能足够接近(

library(tibble)
library(dplyr)
df |>
select(-row_id) |>
colMeans() |>
enframe(name = "stn", value = "percentage")

输出:

# A tibble: 5 × 2
stn     percentage
<chr>   <dbl>
1 stn_1   0.6
2 stn_2   0.2
3 stn_3   0.4
4 stn_4   0.2
5 stn_5   0.2

数据:

library(readr)
df <- read_table("row_id   stn_1 stn_2 stn_3 stn_4 stn_5
1        1     0     1     0     1
2        0     1     0     0     0
3        1     0     0     0     0
4        1     0     1     0     0
5        0     0     0     1     0")

更新:如@akrun所述,我们也可以使用plyr::numcolwise(mean)(df[-1]) %>% gather()

第一个答案:还有一个。老实说@MrFlick这个卑鄙的想法太棒了!!!

library(dplyr)
library(tibble)
df %>% 
mutate(across(-row_id, ~sum(.)/nrow(df))) %>% 
t() %>% 
data.frame() %>% 
slice(-1) %>% 
rownames_to_column("stn") %>% 
select(stn, percentage=X1)
stn percentage
1 stn_1        0.6
2 stn_2        0.2
3 stn_3        0.4
4 stn_4        0.2
5 stn_5        0.2

最新更新