简体   繁体   中英

create date from separate columns with day, month year within a nested table in R

I'm working on hydrological data in nested tables. Besides streamflow (Q) I have dates split into 3 columns (one for days, second for months and third for year).

year_2008 <- list("910" = data.frame(Year = c(2008), Day=c(1:5), Month= c(1, 1, 1, 1 ,1)),
             "950" = data.frame(Year = c(2008), Day=c(1:5), Month= c(1, 1, 1, 1 ,1)),
             "1012" = data.frame(Year = c(2008), Day=c(1:5), Month= c(1, 1, 1, 1 ,1)),
              "1087" = data.frame(Year = c(2008), Day=c(1:5), Month= c(1, 1, 1, 1 ,1)))


year_2009 <- list("910" = data.frame(Year = c(2009), Day=c(1:5), Month= c(1, 1, 1, 1 ,1)),
                  "950" = data.frame(Year = c(2009), Day=c(1:5), Month= c(1, 1, 1, 1 ,1)),
                  "1012" = data.frame(Year = c(2009), Day=c(1:5), Month= c(1, 1, 1, 1 ,1)),
                  "1087" = data.frame(Year = c(2009), Day=c(1:5), Month= c(1, 1, 1, 1 ,1)))

It's a nested table.

year_list <- list (year_2008, year_2009)
names(year_list) <- c("2008", "2009")

I'm trying to gather the information from those 3 columns into a single one which will show a date (in a new column called "date"). I've created a function to create a date column:

transform_date2 <- function(x) {x$date <- as.Date(with(x, paste(x$Day, x$Month, x$Year, sep="-")), "%d-%m-%Y")}

I tried applying that function to the nested table:

result1 <- lapply(year_list, `[[`, transform_date2)

this results in an error: Error in FUN(X[[i]], ...): invalid subscript type 'closure'

I tried doing a loop:

result2 <- for (i in 1:seq_along(year_list)) {transform_date2}

This results in: Warning message: In 1:seq_along(year_list): numerical expression has 2 elements: only the first used

I feel that I'm having problems accessing the correct "level" of the nested table.

My end goal is to keep the current format (nested table), remove the columns Day, Month, Year in each nested table, create the date column in each and keep the Q column. Please help

Since it's a nested list use nested lapply :

year_list <- lapply(year_list, function(x) lapply(x, transform_date2))

where transform_date2 is:

transform_date2 <- function(x) {x$date <- as.Date(with(x, paste(x$Day, x$Month, x$Year, sep="-")), "%d-%m-%Y");x}

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