I have 4 data frames that I created to be a list
dfs <- list(bio_w, bio_k, demo_w, demo_k)
Now what I want to do is move my id column to the very front. I spent hours trying to get it to apply to all 4 dfs using the apply function but I just got error after error so i did it 1 by 1 using:
bio_w <- bio_w %>% relocate(id, .before = 1)
bio_k <- bio_w %>% relocate(id, .before = 1)
demo_w <- demo_w %>% relocate(id, .before = 1)
demo_k <- demo_k %>% relocate(id, .before = 1)
I was trying things like:
dfs2 <- lapply(dfs, FUN = function(x){x[relocate(id, .before = 1)]})
dfs2 <- lapply(dfs %>% relocate(id, .after = 0))
dfs2 <- lapply(dfs, function(x) relocate(id, .after = 0))
but I am getting different errors constantly, including:
Error in UseMethod("relocate") :
no applicable method for 'relocate' applied to an object of class "function"
Error in UseMethod("relocate") :
no applicable method for 'relocate' applied to an object of class "character"
and
Error in lapply(dfs %>% relocate(id, .after = 0)) :
argument "FUN" is missing, with no default
I would greatly appreciate any advice to help me learn to better understand how to use lapply
properly.
Thanks
Your question was solved by @JilberUrbina's answer.
But, since dplyr::relocate
and magrittr::'%>%'
are tidyverse
functions, here's an alternative with apply
's equivalent, purrr::map
, and the recent anonymous function's syntax \(x)
:
(Toy data aux_before
at the end)
library(tidyverse)
# ----------------
aux_after <- map(aux_before, \(x) relocate(x, id, .before = 1))
Output:
# Output
> aux_after
[[1]]
# A tibble: 1 × 3
id name homeworld
<int> <chr> <chr>
1 31 Qui-Gon Jinn NA
[[2]]
# A tibble: 1 × 3
id name homeworld
<int> <chr> <chr>
1 79 Tarfful Kashyyyk
[[3]]
# A tibble: 1 × 3
id name homeworld
<int> <chr> <chr>
1 51 Ki-Adi-Mundi Cerea
[[4]]
# A tibble: 1 × 3
id name homeworld
<int> <chr> <chr>
1 14 Han Solo Corellia
Toy data:
# Toy data
set.seed(123)
aux_before <- starwars %>%
select(name, homeworld) %>%
mutate(id = consecutive_id(name))
aux_before <- map(1:4, \(x) slice_sample(aux_before, n = 1))
> aux_before
[[1]]
# A tibble: 1 × 3
name homeworld id
<chr> <chr> <int>
1 Qui-Gon Jinn NA 31
[[2]]
# A tibble: 1 × 3
name homeworld id
<chr> <chr> <int>
1 Tarfful Kashyyyk 79
[[3]]
# A tibble: 1 × 3
name homeworld id
<chr> <chr> <int>
1 Ki-Adi-Mundi Cerea 51
[[4]]
# A tibble: 1 × 3
name homeworld id
<chr> <chr> <int>
1 Han Solo Corellia 14