I have a list of data frames listofdfs
. To rename the columns of one of the dataframes singledf
in the list, the following code works:
colnames(listofdfs[["singledf"]]) <- paste(colnames(listofdfs[["singledf"]]), "singledf")
Aim
To rename all columns for all data frames in a list of dataframes, listofdfs
, to include the name of the dataframe in all of the respective column names.
Attempt 1
for (i in listofdfs){
colnames(listofdfs[i]) <- paste(colnames(listofdfs[i]), i)
}
This error occurs
Error in `*tmp*`[i] : invalid subscript type 'list'
Attempt 2
for (i in listofdfs){
newnames <- paste(colnames(listofdfs[i]), i)
colnames(bsl) <- newnames
}
This error occurs
No error is printed, however when I check one of the dataframes' columns the column names remain unchanged.
Attempt 3
for (i in listofdfs){
colnames(listofdfs[[i]]) <- paste(colnames(listofdfs[[i]]), i)
}
This error occurs
Error in listofdfs[[i]] : invalid subscript type 'list'
you are almost there. do something like this
this should execute your logic of creating column names without any error.
Why
Because you are expecting
i
to be a index but rather it is adata.frame
itself. Debug usingprint
this is what you get
you cant subscript using a
data.frame
. forloop within
operator in R iterates along the individual elements and not their indexes. Hence we have to useseq_along
Hope this helps.
Below is a code that renames the column names of each data.frame in a list in a way so that names of data.frames are added to original column names.