Vote count:
0
I am using a list of two dataframes that share several similar columns, and I want to be able to convert the class of several columns in each dataframe in one shot using their column names and not the column position.
I’ve searched StockOverflow and found similar questions here: here:Using lists to change columns in multiple dataframes in R and here: applying a function for a list of dataframes. However, I am stuck trying to use multiple column names to convert the dates. Here is a sample data to illustrate my problem:
df1 <- data.frame("t1" = c(20070103, 20070104, 20070105, 20070108, 20070109), "t2" = c(20070110,20070111, 20070112, 20070113, 20070114), A = 1:5))
df2 <- data.frame("t1" = c(20080103, 20080104, 20080105, 20080108, 20080109), "t2" = c(20080110,20080111, 20080112, 20080113, 20080114), B = 1:5)
l <- list(df1 = df1, df2=df2)
So far I’ve found two solutions which I can repeat for every column I want to convert to a date:
#1
l2 <-lapply(l, function(x) transform(x, t1 = as.Date(as.character(t1), "%Y%m%d")))
#2
f <- function(df){
within(df, t1 <- as.date(date))
}
l2 <- lapply(l, f)
However, is there way I can use either method to get multiple columns (not the entire dataframe or list) in one shot and by using column names? I’ve tried the following codes to no avail:
periods <- c( "t1", "t2" )
ls2 <-lapply(ls, function(x) transform(x, periods = as.Date(as.character(periods), "%Y%m%d"))
f <- function(df) {
within(df, t1 <- as.Date(as.character(t1), "%Y%m%d"))
within(df, t2 <- as.Date(as.character(t2), "%Y%m%d"))
}
l2 <- lapply(l, f)
for (i in periods)
l2 <-lapply(l, function(x) transform(x, i = as.Date(as.character(i), "%Y%m%d")))
Aucun commentaire:
Enregistrer un commentaire