Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply function to corresponding elements in list of data frames

Tags:

list

r

I have a list of data frames in R. All of the data frames in the list are of the same size. However, the elements may be of different types. For example,

enter image description here

I would like to apply a function to corresponding elements of data frame. For example, I want to use the paste function to produce a data frame such as

"1a" "2b" "3c"

"4d" "5e" "6f"

Is there a straightforward way to do this in R. I know it is possible to use the Reduce function to apply a function on corresponding elements of dataframes within lists. But using the Reduce function in this case does not seem to have the desired effect.

Reduce(paste,l)

Produces:

"c(1, 4) c(\"a\", \"d\")" "c(2, 5) c(\"b\", \"e\")" "c(3, 6) c(\"c\", \"f\")"

Wondering if I can do this without writing messy for loops. Any help is appreciated!

like image 869
dlaser Avatar asked Dec 20 '22 19:12

dlaser


1 Answers

Instead of Reduce, use Map.

 # not quite the same as your data
 l <- list(data.frame(matrix(1:6,ncol=3)),
           data.frame(matrix(letters[1:6],ncol=3), stringsAsFactors=FALSE))
 # this returns a list
 LL <- do.call(Map, c(list(f=paste0),l))
 #
 as.data.frame(LL)
 #  X1 X2 X3
 # 1 1a 3c 5e
 # 2 2b 4d 6f
like image 89
mnel Avatar answered Dec 22 '22 10:12

mnel