我创建了4个数据框架作为列表

dfs <- list(bio_w, bio_k, demo_w, demo_k)

现在我想做的是将我的id列移动到最前面.我花了几个小时试图使用apply函数将其应用到所有4个dfs,但我遇到了一个又一个的错误,所以我使用以下方式一一执行了:

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)

我正在try 这样的事情:

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))

但我经常遇到不同的错误,包括:

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"

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 underst和 how to use lapply properly.

谢谢

推荐答案

@JilberUrbina的回答解决了您的问题.

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
> 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
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

R相关问答推荐

如何将y轴上的线定位得彼此更近

使用scale_x_continuous复制ggplot 2中的离散x轴

从有序数据中随机抽样

合并DFS列表并将索引提取为新列

有效识别长载体中的高/低命中

使用data.table::fcase()而不是dplyr::case_When()时保持值

比较理论阿尔法和经验阿尔法

在R中,我如何使用滑动窗口计算位置,然后进行过滤?

在R中创建连续的期间

从多面条形图中删除可变部分

将项粘贴到向量中,并将它们分组为x的倍数,用空格分隔

将多个变量组合成宽格式

使用ggplot2中的sec_axis()调整次轴

R -基线图-图形周围的阴影区域

计算使一组输入值最小化的a、b和c的值

如何在使用因子时获得Sankey图的Scale_Fill_Viridis的全范围

如何在条形图中的x和填充变量中包含多个响应变量?

使用函数从R中的列中删除标高

在不重复主题的情况下重新排列组

对一个数据帧中另一个数据帧中的值进行计数