Andy.Jian Andy.Jian - 1 month ago 8
R Question

How to manipulate data.frame object in different list more elegantly?

I have data.frame objects in the list which is the output of my function I implemented. However, I intend to make new list where data.frame object in different list put it together. I tried several way to get my expected output but not much elegant. Does anyone know any useful trick of doing this manipulation efficiently ? Is there any elegant solution to accomplish this task ? Any idea?

This is mini example:

savedList <- list(
foo_saved = data.frame(v1=c(1,6,16), v2=c(4,12,23)),
bar_saved = data.frame(v1=c(7,19,31), v2=c(16,28,41)),
cat_saved = data.frame(v1=c(5,13,26), v2=c(11,21,42))
)

dropedList <- list(
foo_droped = data.frame(v1=c(4,9,20), v2=c(7,15,29)),
bar_droped = data.frame(v1=c(14,26,35), v2=c(21,30,47)),
cat_droped = data.frame(v1=c(18,29,39), v2=c(25,36,48))
)


This is my expected output:

foo <- list(
foo_saved = data.frame(v1=c(1,6,16), v2=c(4,12,23)),
foo_droped = data.frame(v1=c(4,9,20), v2=c(7,15,29))
)

bar <- list(
bar_saved = data.frame(v1=c(7,19,31), v2=c(16,28,41)),
bar_droped = data.frame(v1=c(14,26,35), v2=c(21,30,47))
)

cat <- list(
cat_saved = data.frame(v1=c(5,13,26), v2=c(11,21,42)),
cat_droped = data.frame(v1=c(18,29,39), v2=c(25,36,48))

)


I tried some existing solution but I am not feeling satisfy with it. How can I get my desired output easily ? Is there any efficient, compatible solution for this ? Thanks a lot

Answer

You could combine the two lists, then split on the common part of the names. split() is not the most efficient function ever, but the code for this is very simple.

x <- c(savedList, dropedList)
split(x, sub("_.*", "", names(x)))

This gives the following:

List of 3
 $ bar:List of 2
  ..$ bar_saved :'data.frame':  3 obs. of  2 variables:
  .. ..$ v1: num [1:3] 7 19 31
  .. ..$ v2: num [1:3] 16 28 41
  ..$ bar_droped:'data.frame':  3 obs. of  2 variables:
  .. ..$ v1: num [1:3] 14 26 35
  .. ..$ v2: num [1:3] 21 30 47
 $ cat:List of 2
  ..$ cat_saved :'data.frame':  3 obs. of  2 variables:
  .. ..$ v1: num [1:3] 5 13 26
  .. ..$ v2: num [1:3] 11 21 42
  ..$ cat_droped:'data.frame':  3 obs. of  2 variables:
  .. ..$ v1: num [1:3] 18 29 39
  .. ..$ v2: num [1:3] 25 36 48
 $ foo:List of 2
  ..$ foo_saved :'data.frame':  3 obs. of  2 variables:
  .. ..$ v1: num [1:3] 1 6 16
  .. ..$ v2: num [1:3] 4 12 23
  ..$ foo_droped:'data.frame':  3 obs. of  2 variables:
  .. ..$ v1: num [1:3] 4 9 20
  .. ..$ v2: num [1:3] 7 15 29