I have a df
where some years might ultimately have columns that don't exist. I am looking to use code that allows the columns that do exist to be selected.
df <- tibble::tribble(
~llevel, ~mlevel, ~minorMasterId, ~playerName, ~playerNameRoute,
"ST", "MLB", "sa920245", "Vladimir Guerrero Jr.", "Vladimir Guerrero Jr.",
"MLB", "MLB", "sa3007033", "Wander Franco", "Wander Franco",
"ST", "MLB", "sa919910", "Fernando Tatis Jr.", "Fernando Tatis Jr.",
"ST", "MLB", "sa917930", "Forrest Whitley", "Forrest Whitley"
)
df <- df|>
dplyr::select(Season,
Type,
rank = cOVR,
_rank = cORG,
redraft_rank = Fantasy_Redraft,
dynasty_rank = Fantasy_Dynasty,
playerName,
PlayerId,
minorMasterId)
I am guessing it might utilize some version of any_of
, but I am having a tough time getting to a solution.
I have a df
where some years might ultimately have columns that don't exist. I am looking to use code that allows the columns that do exist to be selected.
df <- tibble::tribble(
~llevel, ~mlevel, ~minorMasterId, ~playerName, ~playerNameRoute,
"ST", "MLB", "sa920245", "Vladimir Guerrero Jr.", "Vladimir Guerrero Jr.",
"MLB", "MLB", "sa3007033", "Wander Franco", "Wander Franco",
"ST", "MLB", "sa919910", "Fernando Tatis Jr.", "Fernando Tatis Jr.",
"ST", "MLB", "sa917930", "Forrest Whitley", "Forrest Whitley"
)
df <- df|>
dplyr::select(Season,
Type,
rank = cOVR,
_rank = cORG,
redraft_rank = Fantasy_Redraft,
dynasty_rank = Fantasy_Dynasty,
playerName,
PlayerId,
minorMasterId)
I am guessing it might utilize some version of any_of
, but I am having a tough time getting to a solution.
1 Answer
Reset to default 3To use any_of()
, you could move column names to a char vector, optionally naming those you want to rename:
cols <- c(
"Season",
"Type",
rank = "cOVR",
_rank = "cORG",
redraft_rank = "Fantasy_Redraft",
dynasty_rank = "Fantasy_Dynasty",
renamed_player_name = "playerName",
"PlayerId",
"minorMasterId")
df|>
dplyr::select(dplyr::any_of(cols))
#> # A tibble: 4 × 2
#> renamed_player_name minorMasterId
#> <chr> <chr>
#> 1 Vladimir Guerrero Jr. sa920245
#> 2 Wander Franco sa3007033
#> 3 Fernando Tatis Jr. sa919910
#> 4 Forrest Whitley sa917930