Question

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

Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top