0

I would like to batch replace 5th column name with filename like this:

for (i in dflist){
names(i)[5]<-i
}

The problem must be in my list, because if I try any method from here I get NULLs. Various other methods complain about vectors or dimensions. How to obtain a data frame list that I can loop over or lapply?

1 Answers1

0
df1 <- data.frame(colA=rnorm(5), colB=rnorm(5), colC=rnorm(5))
df2 <- data.frame(colA=rnorm(5), colB=rnorm(5), colC=rnorm(5))
df3 <- data.frame(colA=rnorm(5), colB=rnorm(5), colC=rnorm(5))

# Create a list with dataframes
dflist <- list(df1=df1,df2=df2,df3=df3)

#If you need to do this for many dataframes and you do not want to manually create names
# you can all dataframes into the list based on the pattern of their names (or you can add all dataframes)
dflist <- mget(ls(pattern = "^df\\d+$"))

for( i in 1:length(dflist)) names( dflist[[i]])[2] <- names(dflist)[i]

dflist
# $df1
# colA        df1       colC
# 1 -0.1422569 -0.9708563 -0.7436538
# 2 -1.4446162  0.5055604 -0.4629691
# 3 -0.3074055  1.0433459  0.1666820
# 4  0.5022005  0.1734464  0.5055267
# 5  1.0109980 -1.6338863  0.8307362
# 
# $df2
# colA        df2        colC
# ...

You can extract these new dataframes from the list and put them back into your environment:

list2env(dflist, .GlobalEnv)
head(df1)
#         colA         df1       colC
#1  1.09331854 -0.25656013 -0.3371509
#2 -0.10231413 -1.57529234  0.1046795
#3 -2.18463139  1.12416514 -0.3130566
#4  0.66743048 -0.84002134  0.8222045
#5 -0.02061098 -0.09697982 -1.7822345
Katia
  • 3,784
  • 1
  • 14
  • 27
  • With this solution, the transformed data frames don't seem to be manipulatable (for example `head()` doesn't work). I would prefer to be able to apply changes to data frames already loaded into the workspace. – anon0328493274 May 16 '18 at 08:15
  • @anon0328493274 It's not clear what you mean by head() does not work. To the bottom of my answer the way you can extract dataframes back into your environment and use head() command to view the first 6 records of each dataframe. If you mean something else other than renaming column names for your dataframe based on dataframe's names you need to be more clear in your question. – Katia May 16 '18 at 10:45
  • The edit helped, but I still need guidance on how to do the first step, namely to populate the `dflist` with csv files from the working directory in a way that will work with your solution. – anon0328493274 May 16 '18 at 11:04