Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
523 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...