Search code examples
rdataframelapplynames

Setting colnames of several data frames based on a list variable


I have a list of multiple data frames which are built the same way. I would like to change the name of the 1 column of each data frame to the name of the data frame itself and append some text. From several different answers I figured lapply and working on lists would be the best way to go.

Example data:

df1 <- data.frame(A = 1, B = 2, C = 3)
df2 <- data.frame(A = 1, B = 2, C = 3)
dfList <- list(df1,df2)

col1 <- names(dfList)

df<-lapply(dfList, function(x) {
names(x)[1:2] <- c(col1[1:length(col1)]"appended text","Col2","Col3");x
})

The problem seems to be with calling the correct entry in the "col1" variable for each data frame within my code. Any ideas on how I should address/ express this correctly? Thanks a lot!


Solution

  • df1<-data.frame(A = 1, B = 2, C = 3)
    df2<-data.frame(A = 1, B = 2, C = 3)
    dfList <- list(df1=df1,df2=df2)
    names(dfList)
    col1 <- names(dfList)
    
    for(i in 1:length(dfList))
      names(dfList[[names(dfList[i])]])[1]<-names(dfList)[i]
    
    dfList