Reputation: 678
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 :)
Upvotes: 1
Views: 46
Reputation: 214947
Just re-select the columns of all the data frames in the same order as your first data frame:
lapply(dfList, `[`, names(dfList[[1]]))
#$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
Upvotes: 4