Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Column names changing when using as.data.frame on a list in R

I have a list that I’m trying to change to a data frame in R. When I do this with as.data.frame it takes the name of the individual lists and adds it to the front of each column name in the new df. Here’s an example of what I’m talking about:

emp.data <- data.frame(
  emp_id = c (1:5), 
  emp_name = c("Rick","Dan","Michelle","Ryan","Gary"))

emp.data2 <- data.frame(
  emp_id2 = c (1:5), 
  emp_name2 = c("Rick","Dan","Michelle","Ryan","Gary"))

total <- list("emp.data" = emp.data, "emp.data2" = emp.data2)

total <- as.data.frame(total)

total now looks like:

  emp.data.emp_id emp.data.emp_name emp.data2.emp_id2 emp.data2.emp_name2
1               1              Rick                 1                Rick
2               2               Dan                 2                 Dan
3               3          Michelle                 3            Michelle
4               4              Ryan                 4                Ryan
5               5              Gary                 5                Gary

I need to keep the names of the dataframes because I use them elsewhere. Is there anyway to make this not happen and have the column names remain unchanged?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks,
Stacy

>Solution :

any of the following will work:

1.

as.data.frame(unname(total))
  emp_id emp_name emp_id2 emp_name2
1      1     Rick       1      Rick
2      2      Dan       2       Dan
3      3 Michelle       3  Michelle
4      4     Ryan       4      Ryan
5      5     Gary       5      Gary
do.call(cbind, unname(total)) 
do.call(data.frame, unname(total))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading