在一个df中使用名称创建另一个数据框的相同列副本

sam*_*amz 4 for-loop copy r dplyr

df <- structure(list(Cars = structure(3:1, .Label = c("Ford ", "Mazda", "Merc"), class = "factor"), Model = structure(c(2L, 1L, 3L), .Label = c("c", "e-class", "gt"), class = "factor"), Color = structure(1:3, .Label = c("Black ", "Blue", "Red"), class = "factor")), class = "data.frame", row.names = c(NA, -3L))
argument <- structure(list(NewVar = structure(3:2, .Label = c("", "SKU", "Vehicle"), class = "factor"), Input = structure(2:3, .Label = c("", "Cars", "Model"), class = "factor")), row.names = 1:2, class = "data.frame")
after <- structure(list(Cars = structure(3:1, .Label = c("Ford ", "Mazda", "Merc"), class = "factor"), Model = structure(c(2L, 1L, 3L), .Label = c("c", "e-class", "gt"), class = "factor"), Color = structure(1:3, .Label = c("Black ", "Blue", "Red"), class = "factor"), Vehicle = structure(3:1, .Label = c("Ford ", "Mazda", "Merc"), class = "factor"), SKU = structure(c(2L, 1L, 3L), .Label = c("c", "e-class", "gt"), class = "factor")), class = "data.frame", row.names = c(NA, -3L))
df
#>    Cars   Model  Color
#> 1  Merc e-class Black 
#> 2 Mazda       c   Blue
#> 3 Ford       gt    Red
argument
#>    NewVar Input
#> 1 Vehicle  Cars
#> 2     SKU Model
after
#>    Cars   Model  Color Vehicle     SKU
#> 1  Merc e-class Black     Merc e-class
#> 2 Mazda       c   Blue   Mazda       c
#> 3 Ford       gt    Red   Ford       gt
Run Code Online (Sandbox Code Playgroud)

我试图for循环遍历各列,并基于“ argument”创建一个副本data.frame。这是我尝试过的方法,但实际上没有用。我有df论点和之后的论点dputs。本质上,该参数具有一个标题为“ new var”和“ input”的列。在论点上,我在“ new var”中有“ Vehicle”,在“ Cars”中有“ input”。这意味着在原始文件中df,复制“汽车”并将其命名为“车辆”。
List是动态的,因此我尝试根据参数的长度将其保留在for循环中,即,如果我也希望将颜色复制为绘画,则进行更改。

for (i in 1:length(argument$Input) ){
  df %>%   
  mutate( paste0(argument[i,1]) =  !!as.name(argument[i,2])
     }
Run Code Online (Sandbox Code Playgroud)

注意,argument[i,1]是指input,因此“变量”是新的列名。在中dplyr,这会产生影响df,因此我认为!!as.name应该拉出已经存在的变量,即“汽车”已经在之前df

akr*_*run 6

我们可以使用“参数”的“输入”列选择感兴趣的列,然后使用rename_at来更改列名称。“参数”数据集列是factor类,character在进行更改时将其转换为。

library(dplyr)
df %>%
    mutate_at(vars(as.character(argument$Input)), list(new= ~ .)) %>% 
    rename_at(vars(matches('new')), ~ as.character(argument[[1]]))
#     Cars   Model  Color Vehicle     SKU
#1  Merc e-class Black     Merc e-class
#2 Mazda       c   Blue   Mazda       c
#3 Ford       gt    Red   Ford       gt
Run Code Online (Sandbox Code Playgroud)

如果我们使用的是OP的for循环使用:=,确保评估(!!)的名称字符串上lhs:=

library(magrittr)
for(i in seq_len(nrow(argument))){
     df %<>%
         mutate(!! as.character(argument[[1]][i]) :=  
                 !! rlang::sym(as.character(argument[[2]][i])))
  }
Run Code Online (Sandbox Code Playgroud)