11

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...

starball
  • 20,030
  • 7
  • 43
  • 238
userk
  • 901
  • 5
  • 11
  • 19

1 Answers1

34

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
Community
  • 1
  • 1
Carl Witthoft
  • 20,573
  • 9
  • 43
  • 73
  • Thanks, this works for my individual data.frames, so it works if I apply it to `data[[1]]$names<-rownames(data[[1]])` but `data` is a list of 6 individual data.frames, I'm looking to find a way to apply something similar to what you have given me but to all of my data.frames in `data`. – userk Aug 23 '13 at 13:08
  • 1
    Oh, this works if I apply it in a for loop! `for (k in 1:length(data)){ data[[k]]$date <- rownames(data[[k]]) }` Thank you for your help – userk Aug 23 '13 at 13:16
  • Is there a way to do this with `lapply()`, not just a for loop? – Boogi Mar 25 '19 at 22:15
  • 1
    @Boogi pretty much any `for` loop can be made into a `*apply` call. In this case you may need an anonymous function defined. See my edits for an example – Carl Witthoft Mar 26 '19 at 12:19