[英]Using assignment operators to create multiple df within for-loop in R
I often use longitudinal data sets, summarise data and put together reports with the summary data in a side-by-side format. 我经常使用纵向数据集,汇总数据并将报告与汇总数据以并排格式放在一起。 To do so, I generally run a chunk of code for the relevant years, create a data frame for each year, then use bind_cols to put the data together.
为此,我通常在相关年份运行一大堆代码,为每年创建一个数据框,然后使用bind_cols将数据放在一起。
I am hoping to use a for-loop so I do not need to modify the code for each year. 我希望使用一个for循环,所以我不需要每年修改代码。 I am trying to use the assignment operator to create multiple data frames while running the loop.
我试图在运行循环时使用赋值运算符创建多个数据帧。 Here is my attempt that is not working:
这是我的尝试不起作用:
d1 <- data.frame(Year = c(2019, 2019, 2019, 2018, 2018),
Group = c("a", "b", "b", "a", "c"))
years <- c(2019, 2018)
for (i in years){
df <- filter(d1$Year == i) %>%
group_by(Group) %>%
summarise(n = n()) %>%
rename(paste0("n_", i) = n)
dat[[i]] <- df
}
Any assistance would be appreciated. 任何援助将不胜感激。
We can filter
with %in%
for multiple values instead of ==
and then take the 'count' 我们可以使用
%in%
filter
多个值而不是==
,然后取'count'
library(dplyr)
d1 %>%
filter(Year %in% years) %>%
count(Group, Year)
If we want to make multiple data.frames 如果我们要制作多个data.frames
d1 %>%
filter(Year %in% years) %>%
group_split(Year) %>%
map(~ .x %>%
count(Group))
d1 <- data.frame(Year = c(2019, 2019, 2019, 2018, 2018),
Group = c("a", "b", "b", "a", "c"))
years <- c(2019, 2018)
for (i in years){
df = d1 %>%
filter(d1$Year == i) %>%
group_by(Group) %>%
summarize(now = n())
assign(paste0("df_", i),df)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.