使用vars函数重命名dplyr中的列时出现charcter向量错误

时间:2018-12-01 17:38:57

标签: r dplyr rename lubridate

我正在尝试获取具有日期的财务数据并创建汇总表。为此,我将数据转换为宽格式,然后要重命名结果新的列,否则它们将显示为日期。

我相信我在使用“ rename_at”时会向“ vars”提供一个字符向量,但它会引发错误,我对此感到困惑。我在这里找到此链接,作为有关如何重命名多列rename example

的示例

所需的输出如下所示:

enter image description here

可复制的示例

library(tidyverse)
library(lubridate)

# data
my_dates <- as.Date(c("2018-05-25", "2018-08-25", "2018-11-25", "2018-05-25", "2018-08-25", "2018-11-25"))
item     <- c("A","A","A","B","B","B")
value    <- c(50:55)

df <- data.frame(my_dates, item, value)

# Dates will become column names and coerced as characters, so need way to refer to them
my_colnames  <- as.character(sort(my_dates, decreasing = TRUE))

# New column names
new_colnames <- c("current", "3M_ago", "6M_ago")

# convert to wide format
df_wide <- df %>%
    spread(key = my_dates, value) %>%
    select(item, my_colnames) %>%
    rename_at(vars(my_colnames) ~ new_colnames)  # throws error here

预先感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

,之前需要一个~~部分类似于匿名函数调用,而不是带有vars

的公式对象
library(tidyverse)
df %>%
   spread(key = my_dates, value) %>%
   select(item, my_colnames) %>%
   rename_at(vars(my_colnames), ~ new_colnames)
#  item current 3M_ago 6M_ago
#1    A      52     51     50
#2    B      55     54     53