简体   繁体   中英

R - Using cast from reshape package to transform list of dataframes

I have created this testframe.

library(lubridate)
set.seed(23) 

date_list = seq(ymd('2000-01-01'),ymd('2003-12-31'),by='day')
testframe = data.frame(Date = date_list)
testframe$Day = substr(testframe$Date, start = 6, stop = 10)
testframe$ABC = rnorm(1461)
testframe$Year = as.numeric(format(testframe$Date,'%Y'))
testframe$Date = NULL
testframe = testframe[,c(ncol(testframe),1:(ncol(testframe)-1))]

My question is how to execute this command in a list of dataframes. This is working for one single dataframe:

library(reshape)
testframe_t = cast(testframe, Year ~ Day)

But when I create a list of dataframes, its not working. Where is my mistake?

df_list = list(testframe, testframe, testframe)

lapply(df_list, function(x) {
  cast(df_list$x$Year ~ df_list$x$Day)})

Any ideas?

Here is the dplyr/tidyr/purrr approach.

library(tidyverse)
testframe1 = data.frame(Date = seq(ymd('2000-01-01'),ymd('2003-12-31'),by='day')) %>% 
  mutate(Day = substr(Date, start = 6, stop = 10),
         ABC = rnorm(1461),
         Year = as.numeric(format(Date,'%Y')),
         Date = NULL) %>% 
  select(Year, Day, ABC)

testframe2 = data.frame(Date = seq(ymd('2004-01-01'),ymd('2007-12-31'),by='day')) %>% 
  mutate(Day = substr(Date, start = 6, stop = 10),
         ABC = rnorm(1461),
         Year = as.numeric(format(Date,'%Y')),
         Date = NULL) %>% 
  select(Year, Day, ABC)


df_list = list(testframe1, testframe2)

df = map_dfr(df_list, ~.x %>% spread(Day, ABC)) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM