Paul
Paul

Reputation: 696

R iterate through list of dataframes to create new column

I have a list of dataframes DFList. For every dataframe in DFList i would like to create a new column X4.

Small Example

X1 <- c(1,2,3,"X","Y")
X2 <- c(100,200,130,120,150)
X3 <- c(1000,250,290,122,170)
DF1 <- data.frame(X1,X2,X3)

X1 <- c(5,6,4,3,9)
X2 <- c(105,205,150,125,175)
X3 <- c(1500,589,560,512,520)
DF2 <- data.frame(X1,X2,X3)

DFList <- list(DF1,DF2)
names(DFList) <- c("DF1","DF2")
DFList

To create a new column by combining values from columns X1, X2, and X3 I created the following function.

MyFUN <- function(V) {
  X4 <- paste(V[1],":",V[2],"-",V[3], sep = "")
  return(X4)
}

However I am having trouble successfully running this function... I attempted the following but the desired X4 column is not being added to the dataframes contained in the list.

print(DFList)

for (DF in DFList){
  for (num in (0:length(DFList))){
    DF["X4"] <- lapply(DF[num], FUN = MyFUN)
  }
}

print(DFList)

Upvotes: 1

Views: 364

Answers (1)

akrun
akrun

Reputation: 886938

We can use lapply to loop through the list elements and transform to create the pasteed components (assuming that we have only 3 columns and the column names are static

lapply(DFList, transform, X4 = paste0(X1, X2, X3))

If we have variable columns

lapply(DFList,  function(x) {x$newCol <- do.call(paste0, x); x})

Upvotes: 3

Related Questions