gpt4 book ai didi

r - 计算R中每列的负值、0值和正值的数量和百分比

转载 作者:行者123 更新时间:2023-12-02 19:24:02 26 4
gpt4 key购买 nike

我有一个玩具数据集,如下:

df <- structure(list(id = 1:11, price = c(40.59, 70.42, 1.8, 1.98, 
65.02, 2.23, 54.79, 54.7, 3.32, 1.77, 3.5), month_pct = structure(c(11L,
10L, 9L, 8L, 7L, 6L, 5L, 4L, 3L, 1L, 2L), .Label = c("-19.91%",
"-8.55%", "1.22%", "1.39%", "1.41%", "1.83%", "2.02%", "2.59%",
"2.86%", "6.58%", "8.53%"), class = "factor"), year_pct = structure(c(4L,
9L, 5L, 3L, 10L, 1L, 11L, 8L, 6L, 7L, 2L), .Label = c("-10.44%",
"-19.91%", "-2.46%", "-35.26%", "-4.26%", "-5.95%", "-6.35%",
"-6.91%", "-7.95%", "1.51%", "1.54%"), class = "factor")), class = "data.frame", row.names = c(NA,
-11L))

输出:

   id  price month_pct year_pct
0 1 40.59 8.53% -35.26%
1 2 70.42 6.58% -7.95%
2 3 1.80 2.86% -4.26%
3 4 1.98 2.59% -2.46%
4 5 65.02 2.02% 1.51%
5 6 2.23 1.83% -10.44%
6 7 54.79 1.41% 1.54%
7 8 54.70 1.39% -6.91%
8 9 3.32 1.22% -5.95%
9 10 1.77 -19.91% -6.35%
10 11 3.50 -8.55% -19.91%

现在我想计算 month_pct 列的正数、0 和负数数量百分比 year_pct,我怎样才能在 R 中做到这一点?

谢谢。

最佳答案

其中一种 dplyrtidyr 可能是:

df %>%
pivot_longer(-c(1:2)) %>%
group_by(name,
value_sign = factor(sign(as.numeric(sub("%", "", value))),
levels = -1:1,
labels = c("negative", "zero", "positive")),
.drop = FALSE) %>%
count() %>%
group_by(name) %>%
mutate(prop = n/sum(n)*100)

name value_sign n prop
<chr> <fct> <int> <dbl>
1 month_pct negative 2 18.2
2 month_pct zero 0 0
3 month_pct positive 9 81.8
4 year_pct negative 9 81.8
5 year_pct zero 0 0
6 year_pct positive 2 18.2

关于r - 计算R中每列的负值、0值和正值的数量和百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62634435/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com