我知道这对于R用户来说相当简单,但是努力完成以下简单任务:
我有这个数据框:
数据
set.seed(123)
df <- data.frame(ID_series=c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18),
year=c(2010,2011,2012,2010,2011,2012,2010,2011,2012,2010,2011,2012,
2010,2011,2012,2010,2011,2012),
IDPlot=c(1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2),
value=runif(18, 0.0, 1.0))
我需要:
谢谢您的建议! 米哈尔
答案 0 :(得分:2)
您可以将数据转换为宽格式,然后使用group_split
将其拆分为不同的数据帧。
library(tidyverse)
out <- df %>%
pivot_wider(names_from = ID_series, values_from = value) %>%
group_split(IDPlot)
out
#[[1]]
# A tibble: 3 x 5
# year IDPlot `1` `2` `3`
# <dbl> <dbl> <dbl> <dbl> <dbl>
#1 2010 1 0.288 0.883 0.528
#2 2011 1 0.788 0.940 0.892
#3 2012 1 0.409 0.0456 0.551
#[[2]]
# A tibble: 3 x 5
# year IDPlot `1` `2` `3`
# <dbl> <dbl> <dbl> <dbl> <dbl>
#1 2010 2 0.457 0.678 0.900
#2 2011 2 0.957 0.573 0.246
#3 2012 2 0.453 0.103 0.0421
或者以其他方式四舍五入,首先进行分割,然后将每个数据帧转换为宽格式。
out <- df %>%
group_split(IDPlot) %>%
map(~pivot_wider(., names_from = ID_series, values_from = value))
如果要在单独的csvs中编写它们,则可以
lapply(seq_along(out), function(x)
write.csv(out[[x]], paste0('df', x, '.csv', row.names = FALSE)))
数据
set.seed(123)
df <- data.frame(ID_series=c(1,1,1,2,2,2,3,3,3,1,1,1,2,2,2,3,3,3),
year=c(2010,2011,2012,2010,2011,2012,2010,2011,2012,2010,2011,2012,
2010,2011,2012,2010,2011,2012),
IDPlot=c(1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2),
value=runif(18, 0.0, 1.0))