0

I merged all data frames from a list in just one data frame.

The dataframes inside the list are called

TAI
NAM
HEE 

and each data frame looks like this

Yr-M   Compound1 Compound 2
2015-01   0.002    0.15
2015-02   0.004    0.02
2015-03   0.01     0.09

when I merge all dataframes with meanall<-do.call(rbind, meaneach) I get

         Yr-M  Compound1  Compound2
TAI.1   2015-01   0.002    0.15
TAI.2   2015-02   0.004    0.02
TAI.3   2015-03   0.01     0.09
  .
  .
  .
NAM.1   2015-01   0.03     0.4
NAM.2   2015-02   0.001    0.005

I would like to get a column with the names of the list and not as rownames (like above), and without the numbers (TAI.1, TAI.2...), I just want the name TAI

So that I get this:

 List    Yr-M  Compound1  Compound2
  TAI   2015-01   0.002    0.15
  TAI   2015-02   0.004    0.02
  TAI   2015-03   0.01     0.09
  .
  .
  .
  NAM   2015-01   0.03     0.4
  NAM   2015-02   0.001    0.005

How can I do this?

2
  • For a moment there I was trying to understand what the mean is doing inside do.call, but I guess you named your list as mean...? You can see why it is bad practice. As for rownames you can not have duplicates. So the best thing to do is convert the rownames to a column and then use gsub to remove the .[0-9]
    – Sotos
    Mar 20, 2019 at 14:48
  • I used a different name, but just changed it here to avoid misunderstandings
    – user195366
    Mar 20, 2019 at 14:52

2 Answers 2

2

Rownames you can not have duplicates. So the best thing to do is convert the rownames to a column and then use gsub to remove the .[0-9], i.e.

df <- do.call(rbind, your_list)
df$list_id <- gsub('\\..*', '', rownames(df))

Note that you can use dplyr or data.table version of rbinding a list which have the option of including the list names as a column, i.e.

dplyr::bind_rows(your_list, .id = 'list_id')
data.table::rbindlist(your_list, idcol = 'list_id')
0

You can add an additional column with the listnames after merging the three lists via do.call:

nameColumn <- data.frame(listName = c(rep(c('TAI','NAM','HEE'),
                                          c(length(TAI),length(NAM),length(HEE) ))
meanall <- cbind(meanall, nameColumn)

If you want the nameColumn to be the first column, just switch arguments in cbind to

meanall <- cbind(nameColumn, meanall)

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.