I have a list of data frames:
all_trials <- list(data1 = data.frame(trial1 = 1:5,
trial2 = 6:10,
trial3 = 11:15,
trial4 = 16:20),
data2 = data.frame(trial2 = 1:4,
trial3 = 5:8,
trial5 = 9:12))
And a list of variables that I would like to select from each of the data frames, preferably with purrr
.
trials_to_select <- list(data1 = c("trial1", "trial3", "trial4"),
data2 = c("trial2", "trial5"))
Desired output:
selected_trials <- list(data1 = data.frame(trial1 = 1:5,
trial3 = 11:15,
trial4 = 16:20),
data2 = data.frame(trial2 = 1:4,
trial5 = 9:12))
$data1
trial1 trial3 trial4
1 1 11 16
2 2 12 17
3 3 13 18
4 4 14 19
5 5 15 20
$data2
trial2 trial5
1 1 9
2 2 10
3 3 11
4 4 12
I found how to select the same columns from each data frame in a list using map(), but I need to select different columns in each data frame.
CodePudding user response:
Map(`[`, all_trials, trials_to_select)
$data1
trial1 trial3 trial4
1 1 11 16
2 2 12 17
3 3 13 18
4 4 14 19
5 5 15 20
$data2
trial2 trial5
1 1 9
2 2 10
3 3 11
4 4 12
CodePudding user response:
With purrr:
purrr::map2(all_trials, trials_to_select, dplyr::select)
$data1
trial1 trial3 trial4
1 1 11 16
2 2 12 17
3 3 13 18
4 4 14 19
5 5 15 20
$data2
trial2 trial5
1 1 9
2 2 10
3 3 11
4 4 12