Reputation: 861
I have a dataframe that is similar to -
Name State A B C
Tom NY 4 2 5
Dick IL 8 1 3
Harry WI 2 6 4
John MD 5 4 9
I want to create a list of dataframes where each dataframe is sorted on either A
or B
or C
, and the resulting dataframe contains the columns Name
, State
and the column sorted on.
lst
$`A`
Name State A
Dick IL 8
Tom NY 4
John MD 5
Harry WI 2
$`B`
Name State B
Harry WI 6
John MD 4
Tom NY 2
Dick IL 1
$`C`
Name State C
John MD 9
Tom NY 5
Harry WI 4
Dick IL 3
I am trying to use lapply -
lst = lapply(df[sapply(df, is.numeric)], function(x){df[order(-x), ]})
but I am getting stuck on how to get the columns I want.
Upvotes: 3
Views: 45
Reputation: 887221
We could use map
to loop through the column names 'A', 'B', 'C', subset the columns of dataset with select
and arrange
(arrange_at
is used here) based on the looped column in descending order
library(tidyverse)
out <- map(LETTERS[1:3], ~ df1 %>%
select(Name, State, .x) %>%
arrange_at(.x, desc))
out
#[[1]]
# Name State A
#1 Dick IL 8
#2 John MD 5
#3 Tom NY 4
#4 Harry WI 2
#[[2]]
# Name State B
#1 Harry WI 6
#2 John MD 4
#3 Tom NY 2
#4 Dick IL 1
#[[3]]
# Name State C
#1 John MD 9
#2 Tom NY 5
#3 Harry WI 4
#4 Dick IL 3
names(out) <- names(df1)[3:5]
In case, we have to automatically check numeric
columns, then use select_if
and extract the names
df1 %>%
select_if(is.numeric) %>%
names %>%
map(~ df1 %>%
select(Name, State, .x) %>%
arrange(desc(!! rlang::sym(.x)))) # another way to evaluate from symbol
Or using lapply
from base R
lapply(names(df1)[3:5], function(x) df1[order(-df1[[x]]), c("Name", "State", x)])
Upvotes: 3