Home > Software engineering >  How to replace rownames of a list of dataframes with values from a list of character strings in R?
How to replace rownames of a list of dataframes with values from a list of character strings in R?

Time:03-04

Let l be a list of two dataframes and n a list of character strings, wherein l and n both have two elements. Also, let the number of rows of each dataframe in l be equal to the length of the vector of character strings in n.

l <- list(data.frame(x = c(1,2,3), y = c(1,2,3)),
          data.frame(x = c(1,2,3,4), y = c(1,2,3,4)))
n <- list(c('a', 'b', 'c'), c('a', 'b', 'c', 'd'))

Suppose we want to replace the rownames of the two dataframes in l with the character strings in n. The desired result would be:

> l
[[1]]
  x y
a 1 1
b 2 2
c 3 3

[[2]]
  x y
a 1 1
b 2 2
c 3 3
d 4 4

I believe one could exploit mapply for this task, but I cannot figure how to do this.

CodePudding user response:

You can use rownames<- and Map as follows

Map(`rownames<-`, l, n)
# or mapply(`rownames<-`, x = l, value = n, SIMPLIFY = FALSE)

Result

#[[1]]
#  x y
#a 1 1
#b 2 2
#c 3 3
#
#[[2]]
#  x y
#a 1 1
#b 2 2
#c 3 3
#d 4 4

rownames<- sets the rownames of x to value. In your case x is a single dataframe in l, and value is a vector from n. This function is applied "to the first elements of each ... argument, the second elements, the third elements, and so on.", from ?mapply.

And "Map is a simple wrapper to mapply which does not attempt to simplify the result", see ?Map

  • Related