Mutate 在自定义函数中的行为不符合预期(变体)
Mutate not behaving as expected inside custom functions (variation)
我的问题类似于 Ariel Polani 和 Tyler Law 的问题,但就我而言,!!sym()
解决方案或 mutate()
中的 !!
解决方案不起作用。这是我的代码:
library(cansim)
library(tidyverse)
add_series <- function(vector_num,first_date,end_date,tseries) {
tmp <- get_cansim_vector(vector_num,first_date,end_date)
tseries <- mutate(tseries,!!sym(vector_num)=tmp$VALUE)
return(tseries)
}
first_date <- as.Date("2011-01-01",format="%Y-%m-%d")
end_date <- as.Date("2019-06-01",format="%Y-%m-%d")
tseries <- data.frame(REF_DATE=seq(first_date,end_date,by="month"))
tseries <- add_series("v42170711",first_date,end_date,tseries)
如果我们在字符串上使用 assignment
,请使用 :=
,这里我们不需要 sym
library(dplyr)
tseries <- tseries %>%
mutate(!!vector_num :=tmp$VALUE)
-完整代码
add_series <- function(vector_num,first_date,end_date,tseries) {
tmp <- get_cansim_vector(vector_num,first_date,end_date)
tseries %>%
mutate(!! vector_num :=tmp$VALUE)
}
add_series("v42170711",first_date,end_date,tseries) %>%
head
# REF_DATE v42170711
#1 2011-01-01 1566882
#2 2011-02-01 1580492
#3 2011-03-01 1566209
#4 2011-04-01 1594096
#5 2011-05-01 1600677
#6 2011-06-01 1613907
我的问题类似于 Ariel Polani 和 Tyler Law 的问题,但就我而言,!!sym()
解决方案或 mutate()
中的 !!
解决方案不起作用。这是我的代码:
library(cansim)
library(tidyverse)
add_series <- function(vector_num,first_date,end_date,tseries) {
tmp <- get_cansim_vector(vector_num,first_date,end_date)
tseries <- mutate(tseries,!!sym(vector_num)=tmp$VALUE)
return(tseries)
}
first_date <- as.Date("2011-01-01",format="%Y-%m-%d")
end_date <- as.Date("2019-06-01",format="%Y-%m-%d")
tseries <- data.frame(REF_DATE=seq(first_date,end_date,by="month"))
tseries <- add_series("v42170711",first_date,end_date,tseries)
如果我们在字符串上使用 assignment
,请使用 :=
,这里我们不需要 sym
library(dplyr)
tseries <- tseries %>%
mutate(!!vector_num :=tmp$VALUE)
-完整代码
add_series <- function(vector_num,first_date,end_date,tseries) {
tmp <- get_cansim_vector(vector_num,first_date,end_date)
tseries %>%
mutate(!! vector_num :=tmp$VALUE)
}
add_series("v42170711",first_date,end_date,tseries) %>%
head
# REF_DATE v42170711
#1 2011-01-01 1566882
#2 2011-02-01 1580492
#3 2011-03-01 1566209
#4 2011-04-01 1594096
#5 2011-05-01 1600677
#6 2011-06-01 1613907