0

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.

2
  • 1
    You can't have duplicate column names i.e. if you are replacing V1 and V2 with 'amostra4A', it will be duplicate names which are not allowed in data.frames. Do you have list of data.frames or just objects created in the global env? Commented Nov 8, 2022 at 17:46
  • Greetings! Usually it is helpful to provide a minimally reproducible dataset for questions here so people can troubleshoot your problems. One way of doing this is by using the dput function. You can find out how to use it here: youtu.be/3EID3P1oisg Commented Nov 15, 2022 at 3:18

1 Answer 1

0

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"))
Sign up to request clarification or add additional context in comments.

2 Comments

Hello, thank you for helping me, but it didn't work. I have multiples files and each with two columns, I whant to concatenate all columns and put the original file name as column name.
Please read the information at the top of the r tag page on how to ask a question. You need to provide a reproducible example that anyone else can run. Since that was not provided I provided one in the answer and it does work on the example I provided.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.