简体   繁体   中英

Create and fill in columns for multiple data frames using lapply in R

I have many data frames organized in a list object on which I want to perform different operations simultaneously. I got lapply running for different tasks, but somehow I couldn't figure out how I can create a new column for each data.frame and assign the values calculated with lapply to the new column. I could use a for loop, but somehow this would defeat the purpose of working with lapply . I'm sure there is a very simple solution to this,but I cannot get my head around this. Here is what I want to do to a single data.frame:

A data frame called lynx has a column called DT which is a date time object. I create a new column which calculates the time difference between two successive values in DT. Last I assign the last row as NA.

n_h <- length(lynx$DT)
lynx$dif_time[1:((n_h)-1)] <- difftime( lynx$DT[2:n_h],lynx$DT[1:(n_h-1)]) lynx$dif_time[n_h] <- NA

Now I have a list composed of 15 data.frames to which I want to do the same. Here is what I have come up with for the dif_time part, but it doesn't work:

lapply(lynx_list,"[[",1)<- lapply(lynx_list,function(x,b) x$dif_time[1:(length(x[,b])-1)]<-difftime( x[,b][2:length(x[,b])],lynx[,b][1:(length(x[,b])-1)]),b)

The problem is this part: lapply(lynx_list,"[[",1)<- , the other lapply part works as intended. But how can I call the specified column in each element of the list?

ml <- list(DF1=data.frame(A=sample(10), B=sample(10)),
       DF2=data.frame(B=sample(10), D=sample(10)),
       DF3=data.frame(H=sample(10), G=sample(10)) )
ml

ml$DF1[,"new"] <- ml$DF1[,1] - ml$DF1[,2]
ml$DF1

mlnew <- lapply(ml, function(x) cbind(x, newcolumn= x[,1] - x[,2] ))
mlnew

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