r - 使用每个项目的名称从列表中创建新列

标签 r dplyr purrr

我有一个数据框列表。我想使用 purrr 遍历它们并进行一些分析。部分分析包括根据列表项的名称重命名变量。这使我能够将文件正确地合并到一个数据框中。我对如何完成这项工作有点困惑。

    library(tidyverse)

# Get names of columns

df <- mtcars %>% 
  as_tibble() %>% 
  select(1:5)

mtcars_names <- df %>% 
  names()

# Split into many dataframes based on columns
mtcars_ls <- df %>% 
  gather(key, value) %>%
  split(.$key)


map2(mtcars_ls, mtcars_names, function(x, y){
  x %>% 
    rename(y = value)
})
#> $cyl
#> # A tibble: 32 x 2
#>    key       y
#>    <chr> <dbl>
#>  1 cyl       6
#>  2 cyl       6
#>  3 cyl       4
#>  4 cyl       6
#>  5 cyl       8
#>  6 cyl       6
#>  7 cyl       8
#>  8 cyl       4
#>  9 cyl       4
#> 10 cyl       6
#> # … with 22 more rows
#> 
#> $disp
#> # A tibble: 32 x 2
#>    key       y
#>    <chr> <dbl>
#>  1 disp   160 
#>  2 disp   160 
#>  3 disp   108 
#>  4 disp   258 
#>  5 disp   360 
#>  6 disp   225 
#>  7 disp   360 
#>  8 disp   147.
#>  9 disp   141.
#> 10 disp   168.
#> # … with 22 more rows
#> 
#> $drat
#> # A tibble: 32 x 2
#>    key       y
#>    <chr> <dbl>
#>  1 drat   3.9 
#>  2 drat   3.9 
#>  3 drat   3.85
#>  4 drat   3.08
#>  5 drat   3.15
#>  6 drat   2.76
#>  7 drat   3.21
#>  8 drat   3.69
#>  9 drat   3.92
#> 10 drat   3.92
#> # … with 22 more rows
#> 
#> $hp
#> # A tibble: 32 x 2
#>    key       y
#>    <chr> <dbl>
#>  1 hp      110
#>  2 hp      110
#>  3 hp       93
#>  4 hp      110
#>  5 hp      175
#>  6 hp      105
#>  7 hp      245
#>  8 hp       62
#>  9 hp       95
#> 10 hp      123
#> # … with 22 more rows
#> 
#> $mpg
#> # A tibble: 32 x 2
#>    key       y
#>    <chr> <dbl>
#>  1 mpg    21  
#>  2 mpg    21  
#>  3 mpg    22.8
#>  4 mpg    21.4
#>  5 mpg    18.7
#>  6 mpg    18.1
#>  7 mpg    14.3
#>  8 mpg    24.4
#>  9 mpg    22.8
#> 10 mpg    19.2
#> # … with 22 more rows
Created on 2019-09-03 by the reprex package (v0.3.0)

最佳答案

purrr 中实际上有一个名为 imap 的不错的函数,它似乎可以满足您的需要。它遍历列表的元素 (.x) 和名称 (.y):

df <- mtcars %>% 
  select(1:5)

# Split into many dataframes based on columns and create a named list
mtcars_ls <- df %>% 
  gather(key, value) %>%
  split(.$key) %>% 
  set_names(names(df))

imap(mtcars_ls, function(x,y) {
  x %>% 
    rename(!!quo_name(y) := value)
})

!!quo_name:= 允许对名称字符串进行整洁评估。为了使它更简单,您可以使用速记符号:

imap(mtcars_ls, ~ rename(.x, !!quo_name(.y) := value))

关于r - 使用每个项目的名称从列表中创建新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57773004/

相关文章:

r - 基于组和时间的值的共现(矩阵)

R嵌套模型: create column of model formulas

r - Shiny & ggplot : Numeric variables not recognized in ggplot's aes() mapping statement

r - 从 R 中的频率表获取数组(或标记向量)

r - 具有 NA 值的数据框中列的均值和 SD

r - Magritttr + lapply,其中第一个参数不是 LHS

r - 根据 R 中的列表列表更改列

r - 计算数据框中给定变量的均值和标准差

r - 从数据框中的前一列中减去每一列

r - 如何识别两个数据矩阵之间的哪些列和行匹配?