Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rownames as column in list of dataframes

Tags:

list

r

rowname

I'd like to create a column year for each dataframe in a list based on its rownames. This question has been asked before on SO but unfortunately the answer doesn't help. So, is there a way to do it?

mylist <- list(structure(list(a = 1:10), .Names = "a", row.names = 1991:2000, class = "data.frame"), 
            structure(list(a = 1:10), .Names = "a", row.names = 1992:2001, class = "data.frame"))

Expected outcome:

[[1]]
      a year
1991  1 1991
1992  2 1992
1993  3 1993
1994  4 1994
1995  5 1995
1996  6 1996
1997  7 1997
1998  8 1998
1999  9 1999
2000 10 2000

[[2]]
      a year
1992  1 1992
1993  2 1993
1994  3 1994
1995  4 1995
1996  5 1996
1997  6 1997
1998  7 1998
1999  8 1999
2000  9 2000
2001 10 2001
like image 667
erc Avatar asked Feb 16 '16 11:02

erc


People also ask

Can you include an R list as a column of a data frame?

Now to add a list as a column, create a list with required values. Then, use the name of the data frame and the new column separated by $ and assign this to the list so created. This will assign the list to the column name given and then add it to the dataframe.

How do you make a Rowname a column in R?

Method 1: Using row. row.name() function is used to set and get the name of the DataFrame. Apply the row.name() function to the copy of the DataFrame and a name to the column which contains the name of the column with the help of the $ sign.

How do I combine a list of Dataframes into one in a DataFrame in R?

To combine data frames stored in a list in R, we can use full_join function of dplyr package inside Reduce function.

Can a list be an element in a DataFrame R?

If a list has the same length of elements (not sub-elements) as the length of each vector for which we want to create the data frame then we first need to create the data frame of vectors then we can easily add the list into the data frame.


2 Answers

Here's another option:

lapply(mylist, function(df) transform(df, year = rownames(df)))

Just for fun, you could also use dplyr's add_rownames function:

lapply(mylist, dplyr::add_rownames, 'year')
like image 90
talat Avatar answered Sep 20 '22 07:09

talat


We can use Map

Map(cbind, mylist, year= lapply(mylist, rownames))
like image 20
akrun Avatar answered Sep 23 '22 07:09

akrun