我有按地区划分的不同候选人的选举结果。来源有每个候选人的票数和每个选区的总票数。我想添加每个候选人在每个选区获得的选票百分比的变量。
我已经成功地使用mutatewithacross将投票计数替换为百分比,但是在尝试使用参数创建新变量时出现错误.names(即我希望获得新变量,,,,cand1_pct... cand2_pct)。
library(tidyverse)
df <- data.frame(district = 1:3,
cand1 = c(12, 2, 14),
cand2 = c(2, 6, 23),
cand3 = c(3, 16, 2),
total = c(17, 24, 39))
df %>%
mutate(across(2:4, ~ .x/total*100))
#> district cand1 cand2 cand3 total
#> 1 1 70.588235 11.76471 17.647059 17
#> 2 2 8.333333 25.00000 66.666667 24
#> 3 3 35.897436 58.97436 5.128205 39
df %>%
mutate(across(2:4, ~ .x/total*100, .names = "{.col}_pct"))
#> Error: …Run Code Online (Sandbox Code Playgroud)