gpt4 book ai didi

r - 在 dplyr mutate 中,如何使用变量分配新的列名?

转载 作者:行者123 更新时间:2023-12-02 18:05:11 25 4
gpt4 key购买 nike

我可以在 dplyr mutate 中使用变量来表示列名,只要它在计算部分的右侧即可。这很好用:

library(dplyr)
var <- "mass"
x <- starwars %>%
mutate(height = height * 2,
mass = get(var) * 2)

但是,如果我尝试使用变量来表示新的列名称(即在左侧),它会抛出错误。例如,这会导致错误:

var <- "mass"
x <- starwars %>%
mutate(height = height * 2,
get(var) = get(var) * 2)

如何在 mutate 中使用变量作为列名?

最佳答案

!! 中使用 := 运算符 - 我们可以使用 [[ 而不是 get使用 .data 代词提取(或转换为 symbol 并求值 (!!)

library(dplyr)
starwars %>%
mutate(height = height * 2,
!! var := .data[[var]] * 2)
#or convert to symbol and evaluate
# !! var := !! rlang::sym(var) * 2)
#or use `{{}}`
# {{var}} := !! rlang::sym(var) * 2)

-输出

# A tibble: 87 × 14
name height mass hair_color skin_color eye_color birth_year sex gender homeworld species films vehicles starships
<chr> <dbl> <dbl> <chr> <chr> <chr> <dbl> <chr> <chr> <chr> <chr> <list> <list> <list>
1 Luke Skywalker 344 154 blond fair blue 19 male masculine Tatooine Human <chr [5]> <chr [2]> <chr [2]>
2 C-3PO 334 150 <NA> gold yellow 112 none masculine Tatooine Droid <chr [6]> <chr [0]> <chr [0]>
3 R2-D2 192 64 <NA> white, blue red 33 none masculine Naboo Droid <chr [7]> <chr [0]> <chr [0]>
4 Darth Vader 404 272 none white yellow 41.9 male masculine Tatooine Human <chr [4]> <chr [0]> <chr [1]>
5 Leia Organa 300 98 brown light brown 19 female feminine Alderaan Human <chr [5]> <chr [1]> <chr [0]>
6 Owen Lars 356 240 brown, grey light blue 52 male masculine Tatooine Human <chr [3]> <chr [0]> <chr [0]>
7 Beru Whitesun lars 330 150 brown light blue 47 female feminine Tatooine Human <chr [3]> <chr [0]> <chr [0]>
8 R5-D4 194 64 <NA> white, red red NA none masculine Tatooine Droid <chr [1]> <chr [0]> <chr [0]>
9 Biggs Darklighter 366 168 black light brown 24 male masculine Tatooine Human <chr [1]> <chr [0]> <chr [1]>
10 Obi-Wan Kenobi 364 154 auburn, white fair blue-gray 57 male masculine Stewjon Human <chr [6]> <chr [1]> <chr [5]>
# … with 77 more rows

关于r - 在 dplyr mutate 中,如何使用变量分配新的列名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73430252/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com