DarrenRhodes
DarrenRhodes

Reputation: 1503

List of Dataframes First Column to rownames

I have ...

X  <- list(df1  <- data.frame(A=c("CC","CC(=O)C","CC(=O)O"),conc=c(1.0,2.2,1.0),Vol=c(2,4.5,6),stringsAsFactors=FALSE), df2  <- data.frame(A=c("COC","O=CC"),conc=c(2.0,3.2),Vol=c(10,23),stringsAsFactors=FALSE))
X
[1]]
        A conc Vol
1      CC  1.0 2.0
2 CC(=O)C  2.2 4.5
3 CC(=O)O  1.0 6.0

[[2]]
     A conc Vol
1  COC  2.0  10
2 O=CC  3.2  23

and I want to change the first column to rownames.

I have tried the obvious,

X <-lapply(X,function(a) {rownames(a)  <- a$A})

but this doesn't work ...

I began experimenting with the mapply function but I didn't get very far ...

Upvotes: 2

Views: 926

Answers (2)

Jay Silverman
Jay Silverman

Reputation: 121

This is possible using dplyr and tibble column_to_rownames

X  <- list(df1  <- data.frame(A=c("CC","CC(=O)C","CC(=O)O"),conc=c(1.0,2.2,1.0),Vol=c(2,4.5,6),stringsAsFactors=FALSE), df2  <- data.frame(A=c("COC","O=CC"),conc=c(2.0,3.2),Vol=c(10,23),stringsAsFactors=FALSE))

library(dplyr)
library(tibble)

X <- lapply(X, column_to_rownames, "A")

Upvotes: 2

Adam Spannbauer
Adam Spannbauer

Reputation: 2757

Assuming when you said, "I want to change the first column to rownames" that you want to define the rownames with column A and drop column A.

lapply(X, function(df) {
    #new df without rowname col
    df_out <- df[,-1]
    #set rownames as first col from input df
    rownames(df_out) <- df[[1]]
    df_out
})

If you want to set column A to the current rownames then the code in @Sotos comment is a possible answer.

Upvotes: 2

Related Questions