Mark
Mark

Reputation: 1569

R lapply on list of dataframes resetting rownames

You can reset the rownames in a data frame by running

>rownames(df) <- NULL

I have a list of dataframes and want to reset all the rownames on every dataframe in the list, I tried

>newlist <- llply(mylist, function(df) { rownames(df) <- NULL })

Bu tit doesn't work, returns a list of NULLS and the original remains unchanged.

Upvotes: 4

Views: 3022

Answers (2)

G. Grothendieck
G. Grothendieck

Reputation: 270428

Use rownames<- :

newlist <- lapply(mylist, "rownames<-", NULL)

Upvotes: 5

Roland
Roland

Reputation: 132999

This is a job for the base function lapply; you don't need to load plyr. You also need to make sure that your anonymous function returns something.

df1 <- data.frame(a=1:10)
rownames(df1) <- letters[1:10]

df2 <- data.frame(b=1:10)
rownames(df2) <- LETTERS[1:10]

mylist <- list(df1,df2)

mylist <- lapply(mylist,function(DF) {rownames(DF) <- NULL; DF})

Upvotes: 9

Related Questions