Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert row names in multiple data frames to column in data frame

I have a list of .csv files that I have read in to R and placed in a large data frame called data that consists of 6 data.frames which are the 6 files in filenames. My code so far is:

filenames <- list.files( paste(mainDirInput,sep=""), pattern="Out.*csv", full.names=TRUE) 
data = lapply(filenames, function(f) {
wb = read.csv(f, header=TRUE)
})

The row names and column names in each data.frame are exactly the same, I would like to extract the row names and instead have them as the first column in R. An example of one of my data frames would be like this:

            w    x    y    z
2012 01     12   43   87   09
2012 02     14   53   75   76
2012 03     76   34   76   28
2012 04     41   36   85   16
  :         :    :    :    :
  :         :    :    :    :

I need to be able to use this code on other files as well, so I can't simply just create a new column with the values 2012 01, 2012 02, 2012 03...

like image 991
userk Avatar asked Aug 23 '13 12:08

userk


People also ask

How do I change a row name to a column?

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 convert rows to columns in R?

Rotating or transposing R objects frame so that the rows become the columns and the columns become the rows. That is, you transpose the rows and columns. You simply use the t() command.

How do I combine a list of data frames in R?

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

How do I get the row names for a DataFrame in R?

A data frame's rows can be accessed using rownames() method in the R programming language.


1 Answers

Youve got a dataframe with columns named "w,x,y,z" . Just do

data$names <- rownames(data) 

to add a new column.

edit

In response to Boogie's query, here's lapply with an anonymous function to do the loop.

   foo = as.data.frame(matrix(1:15,3,5))
    rownames(foo) <-c('frist','prime','lastly')
    foo
    bar = list(foo,t(foo), rbind(foo,foo))
    bar[[1]] = as.data.frame( foo)
    bar[[2]] =data.frame( t(foo))
    bar[[3]] = data.frame(rbind(foo,foo))
    bar
    bar = lapply(bar,FUN= function(x) { x$date <-rownames(x);return(x)})
    bar
like image 65
Carl Witthoft Avatar answered Oct 09 '22 16:10

Carl Witthoft