[英]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).除了流(Q)之外,我将日期分为 3 列(一列表示天,第二列表示月,第三列表示年)。
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").我正在尝试将这 3 列中的信息收集到一个单独的列中,该列将显示一个日期(在一个名为“日期”的新列中)。 I've created a function to create a date column:我创建了一个 function 来创建一个日期列:
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:我尝试将 function 应用于嵌套表:
result1 <- lapply(year_list, `[[`, transform_date2)
this results in an error: Error in FUN(X[[i]], ...): invalid subscript type 'closure'这会导致错误: FUN(X[[i]], ...) 中的错误:无效的下标类型“闭包”
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这将导致:警告消息:在 1:seq_along(year_list):数值表达式有 2 个元素:仅使用第一个元素
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.我的最终目标是保持当前格式(嵌套表),删除每个嵌套表中的 Day、Month、Year 列,在每个嵌套表中创建日期列并保留 Q 列。 Please help请帮忙
Since it's a nested list use nested lapply
:因为它是一个嵌套列表,所以使用嵌套lapply
:
year_list <- lapply(year_list, function(x) lapply(x, transform_date2))
where transform_date2
is:其中transform_date2
是:
transform_date2 <- function(x) {x$date <- as.Date(with(x, paste(x$Day, x$Month, x$Year, sep="-")), "%d-%m-%Y");x}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.