How can I use a file name as column name in R?

292 Views Asked by At

I have multiple files to concatenate its columns in a dataframe, but for each column I need to use the file name as column name. How should I do it?

For example:

In the file "amostra4A" I have two columns named "V1" and "V2", but I want to replace it for the file name and repeat the same way for the last files.

Sorry for same mistakes, I'm new in R.

1

There are 1 best solutions below

2
G. Grothendieck On

Put the data frames into a list L such that the name of each data frame is the name you want to use. We will use BOD which comes with R. Convert the list to a data frame and change the names.

L <- list(A = BOD, B = BOD)
DF <- as.data.frame(L)
names(DF) <- sub("\\..*", "", names(DF))
DF
##   A    A B    B
## 1 1  8.3 1  8.3
## 2 2 10.3 2 10.3
## 3 3 19.0 3 19.0
## 4 4 16.0 4 16.0
## 5 5 15.6 5 15.6
## 6 7 19.8 7 19.8

That said it is normally assumed that column names in a data frame are unique and you are bound to run into subsequent problems if you do the above. Better would be to use a prefix of the A or B name followed by the column name so that the names are unique.

as.data.frame(L)
##   A.Time A.demand B.Time B.demand
## 1      1      8.3      1      8.3
## 2      2     10.3      2     10.3
## 3      3     19.0      3     19.0
## 4      4     16.0      4     16.0
## 5      5     15.6      5     15.6
## 6      7     19.8      7     19.8

Note that if the data frames are sitting loose in the global environment an alternative to creating L is:

A <- BOD
B <- BOD
L <- mget(c("A", "B"))