I have a list with approximately 50 (slots) - dataframes. Each and every element of this list (dataframe) has 10 columns, 3 of which correspond to "year", "month" and "day". How can I cbind those three columns into one (by creating new column), in every dataframe of this list, and convert them at the same time to as.Date format without using the dplyr package .
I'm sending a reproducible example:
city_A <- data.frame(year = c(1995,1996,1997),month = c(5,6,9),day = c(1,5,8),ozone = c(0.5,0.9,0.12))
city_D <- data.frame(year = c(1982,1959,1909),month = c(3,10,12),day = c(21,24,30),ozone = c(1.5,2.9,3.14))
town_list <- list(city_A,city_D)
The expected outcome is something like this:
[[1]]
date year month day ozone
1 1995-05-01 1995 5 1 0.5
2 1996-06-05 1996 6 5 0.9
3 1997-09-08 1997 9 8 0.12
[[2]]
date year month day ozone
1 1982-03-21 1982 3 21 1.5
2 1959-10-24 1959 10 24 2.9
3 1909-12-30 1909 12 30 3.14
CodePudding user response:
We can use ISOdate to transform to create the Date class
lapply(town_list, transform, date = as.Date(ISOdate(year, month, day)))
If it needs to be the first column, either cbind or use column indexing afterwards
lapply(town_list, \(x)
cbind(date = with(x, as.Date(ISOdate(year, month, day))), x))
CodePudding user response:
Use do.call(rbind, x)
city_A <- data.frame(year = c(1995,1996,1997),month = c(5,6,9),day = c(1,5,8),ozone = c(0.5,0.9,0.12))
city_D <- data.frame(year = c(1982,1959,1909),month = c(3,10,12),day = c(21,24,30),ozone = c(1.5,2.9,3.14))
town_list <- list(city_A,city_D)
do.call(rbind, town_list)
#> year month day ozone
#> 1 1995 5 1 0.50
#> 2 1996 6 5 0.90
#> 3 1997 9 8 0.12
#> 4 1982 3 21 1.50
#> 5 1959 10 24 2.90
#> 6 1909 12 30 3.14
Created on 2022-02-03 by the reprex package (v2.0.1)
