使用mutate_向dataframe添加新列,其中列名由变量指定

plu*_*uke 5 r dataframe dplyr

我有一个数据框,我想添加一列,其中列由变量名定义:

df <- diamonds
NewName <- "SomeName"
df <- df %>% mutate_(paste0(NewName," = \"\""))
Run Code Online (Sandbox Code Playgroud)

这给了我以下错误:

Error: attempt to use zero-length variable name
Run Code Online (Sandbox Code Playgroud)

我已经看到很多mutate_用于更改列名的示例,但不是动态创建列.有帮助吗?

Mar*_*son 3

该问题与对语句进行评估的时间有关。据我了解, 的目标mutate_不是重新创建 的语法mutate,例如使用pasteto create mutate(SomeName = "")。相反,它是允许函数的生成通过。您的方法失败的原因是(我相信)它正在寻找名为 的函数""

相反,您需要传入一个可以计算的函数(在这里,我用作paste占位符)并使用变量设置该列的名称。这应该有效:

df <- diamonds
NewName <- "SomeName"
df <- df %>% mutate_(.dots = setNames("paste('')",NewName))
Run Code Online (Sandbox Code Playgroud)

这还允许更多控制,例如,您可以粘贴cutcolor

df <- df %>% mutate_(.dots = setNames("paste(cut, color)",NewName))
Run Code Online (Sandbox Code Playgroud)

给出:

   carat       cut color clarity depth table price     x     y     z    SomeName
   <dbl>     <ord> <ord>   <ord> <dbl> <dbl> <int> <dbl> <dbl> <dbl>       <chr>
1   0.23     Ideal     E     SI2  61.5    55   326  3.95  3.98  2.43     Ideal E
2   0.21   Premium     E     SI1  59.8    61   326  3.89  3.84  2.31   Premium E
3   0.23      Good     E     VS1  56.9    65   327  4.05  4.07  2.31      Good E
4   0.29   Premium     I     VS2  62.4    58   334  4.20  4.23  2.63   Premium I
5   0.31      Good     J     SI2  63.3    58   335  4.34  4.35  2.75      Good J
6   0.24 Very Good     J    VVS2  62.8    57   336  3.94  3.96  2.48 Very Good J
7   0.24 Very Good     I    VVS1  62.3    57   336  3.95  3.98  2.47 Very Good I
8   0.26 Very Good     H     SI1  61.9    55   337  4.07  4.11  2.53 Very Good H
9   0.22      Fair     E     VS2  65.1    61   337  3.87  3.78  2.49      Fair E
10  0.23 Very Good     H     VS1  59.4    61   338  4.00  4.05  2.39 Very Good H
Run Code Online (Sandbox Code Playgroud)

(值得注意的是,我还得到了第一次使用的初始语法,随后出现了后续的失败。值得深入研究。)