Jerry.Shad Jerry.Shad - 27 days ago 19
R Question

How to easily manipulate the data.frame in the list let them have same pattern?

I implement function that return list of data.frame where order of the index vector in data.frame is different. However, I intend to manipulate this list that let second, third data.frame has same pattern with first data.frame in the list. Because result is in the list, so I want to manipulate this list easily let data.frame objects has same pattern. How can I make this happen easily ? Does anyone knows any useful trick of manipulating list easily ? Thanks in advance.

the output of my custom function is :

dfList <- list(
df_1 = data.frame(hola = c(1,2,3), ciao=c(NA,1,2), bonjour=c(1,1,2)),
df_2 = data.frame(ciao = c(1,2,3), hola=c(2,3,NA), bonjour=c(1,2,4)),
df_3 = data.frame(bonjour = c(1,2,3,4), hola=c(2,3,NA,NA), ciao=c(1,2,NA,3))
)


I intend to make second, third data.frame has same pattern with first data.frame in the list. How can I easily manipulate data.frame has same pattern in the list?

desired output could be:

$df_1
hola ciao bonjour
1 1 NA 1
2 2 1 1
3 3 2 2

$df_2
hola ciao bonjour
1 2 1 1
2 3 2 2
3 NA 3 4

$df_3
hola ciao bonjour
1 2 1 1
2 3 2 2
3 NA NA 3
4 NA 3 4


I know it is easier if data.frame is not in the list, so just using names() to let them have same pattern. But the point is data.frame in the list as an output now, so I intend to manipulate this list nicely instead of access each data.frame three time and use names() function. How can I make this happen ? How can I achieve my desired output ? How can I get more dynamic solution on that? Thanks a lot :)

Answer

We can use

lapply(dfList, function(x) x[names(dfList[[1]])])