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... 
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.
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.
To combine data frames stored in a list in R, we can use full_join function of dplyr package inside Reduce function.
A data frame's rows can be accessed using rownames() method in the R programming language.
Youve got a dataframe with columns named "w,x,y,z" . Just do
data$names <- rownames(data) 
to add a new column.
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
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With