gpt4 book ai didi

r - 按组基 R 计算随时间变化的百分比

转载 作者:行者123 更新时间:2023-12-05 04:04:42 24 4
gpt4 key购买 nike

感谢对此的任何帮助,我正在尝试重新学习一些基础知识。

这里有一些示例代码可以解决我的问题,它来自受伤 worker 的数据库。

Area <- c("Connecticut", "Maine", "Massachusetts", "New Hampshire", "Texas", "Arizona", "California", "Washington")
Region <- c("Northeast", "Northeast", "Northeast", "Northeast", "South", "South", "West", "West")
X2004 <- c(0,1,4,1,3,4,2,2)
X2005 <- c(1,0,6,2,0,1,0,2)
X2006 <- c(0,0,1,1,2,1,0,0)
df1 <- data.frame(Area, Region, X2004, X2005, X2006)

我想在 Base R 中显示从 2004-2005 的两年平均值到 2006 年的单一年份的百分比变化。我能够使用 tidyverse 包解决这个问题,但这感觉就像使用拐杖一样。这是我目前所拥有的:

df2 <- reshape(df1, 
idvar=c("Area"),
v.names="count",
varying=c("X2004","X2005","X2006"),
direction="long",
times=2004:2006,
timevar="year")
df3 <- df2 %>% group_by(Region, year) %>%
summarise(total_count = sum(count))
df3$pre <- ifelse(df3$year<=2005, 1, 0)
df3 %>%
group_by(Region) %>%
summarise(mean_count_pre = mean(total_count[pre==1]),
mean_count_post = mean(total_count[pre==0]),
pct_change = 100*(mean_count_post - mean_count_pre) / mean_count_pre)

关于如何在不依赖 tidyverse 或 dplyr 的情况下解决这个问题的任何想法?非常感谢这方面的帮助,我在 tidyverse 中学习了 R,我正在努力更好地理解基础知识。

最佳答案

使用您的 df2 作为输入,我们可以这样只使用 R 基本函数:

> # creating `total_count`
> df3<- df2
> df3$total_count <- with(df2, ave(count, Region, year, FUN="sum"))
>
> # creating `pre`
> df3$pre <- ifelse(df3$year<=2005, "pre", "post")
>
> # creating "mean_count_pre" and "mean_count_post"
> output <- aggregate(total_count ~ Region+pre, data=df3, FUN="mean")
> colnames(output)[3] <- "mean_count"
> output_wide <- reshape(output, v.names="mean_count", idvar="Region", timevar = "pre", direction = "wide")
>
> # creating `pct_change`
> output_wide <- transform(output_wide, pct_change=(mean_count.post-mean_count.pre)/mean_count.pre)
> output_wide
Region mean_count.post mean_count.pre pct_change
1 Northeast 2 7.5 -0.7333333
2 South 3 4.0 -0.2500000
3 West 0 3.0 -1.0000000

关于r - 按组基 R 计算随时间变化的百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52192972/

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