使用cross和.names进行更改:“胶水无法将函数插值到字符串中”错误

问题描述

我有按地区划分的不同候选人的选举结果。来源具有每个候选人的票数和每个地区的投票总数。我想为每个候选人在每个地区获得的选票百分比添加变量。

我已经成功地将mutateacross一起使用,以百分比代替了投票数,但是在尝试使用.names参数创建新变量时出现错误(即我希望获得新的变量cand1_pctcand2_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: Problem with `mutate()` input `..1`.
#> x glue cannot interpolate functions into strings.
#> * object '.col' is a function.
#> i Input `..1` is `across(2:4,~.x/total * 100,.names = "{.col}_pct")`.

reprex package(v0.3.0)于2020-08-12创建

我首先认为这是对across.names应该如何工作的误解,但是当我使用across vignette中的示例时,得到同样的错误。我已经在本地计算机和RStudio云上进行了尝试。 dplyr版本1.0.1。

library(dplyr)

iris %>%
  group_by(Species) %>%
  summarise(across(starts_with("Sepal"),mean,.names = "mean_{.col}"))
#> Error: Problem with `summarise()` input `..1`.
#> x glue cannot interpolate functions into strings.
#> * object '.col' is a function.
#> i Input `..1` is `across(starts_with("Sepal"),.names = "mean_{.col}")`.
#> i The error occurred in group 1: Species = "setosa".

reprex package(v0.3.0)于2020-08-12创建

解决方法

根据?across,它不是.col,而只是col

.names-对于单个函数,缺省值(NULL)等效于“ {col}”,对于.fns使用列表,缺省值(NULL)等效于“ {col} _ {fn}”。

library(dplyr)
df %>% 
   mutate(across(2:4,~ .x/total*100,.names = "{col}_pct"))
#  district cand1 cand2 cand3 total cand1_pct cand2_pct cand3_pct
#1        1    12     2     3    17 70.588235  11.76471 17.647059
#2        2     2     6    16    24  8.333333  25.00000 66.666667
#3        3    14    23     2    39 35.897436  58.97436  5.128205
,

...事情已经改变。

根据最新的?across中的dplyr 1.0.2,现在建议使用.col,而不是col

.names-一个粘合规范,描述如何命名输出列。这可以使用{.col}代表所选的列名称,并使用{.fn}代表所应用函数的名称。对于单功能情况,默认值(NULL)等效于“ {.col}”;对于将.fns使用列表的情况,默认值等于“ {.col} _ {。fn}”。

更多信息和用例可以在这里找到:stackoverflow: Using functions of multiple columns in dplyr

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...