12
我試圖混合常量和引用變量名,如使用lazyeval::interp
在Non-standard evaluation vignette建議瞭解標準的評價。R:在mutate_
下面是一個例子,做什麼,我想:
# create sample dataset
df_foo = data_frame(
`(Weird) Variable name` = 100,
group_var = sample(c("Yes", "No"), size = 100, replace = TRUE)
)
# function to update the value of weirdly named variable
update_var_1 = function(var_name) {
df_foo %>%
mutate_(
"(Weird) Variable name" =
interp(quote(ifelse(group_var_val == "Yes", var_name_val/10, var_name_val/20)),
group_var_val = as.name("group_var"),
var_name_val = as.name(var_name))
)
}
# test the function
update_var_1("(Weird) Variable name") %>%
head(n = 20)
請注意,我已經指派了懶惰評估的特徵向量("(Weird) Variable name"
)的結果。但是,當我將懶惰評估的結果分配給var_name
並將其分配給一個文字"var_name"
。有人可以幫助理解這種行爲嗎?
# function to update the value of weirdly named variable
update_var_2 = function(var_name) {
df_foo %>%
mutate_(
var_name =
interp(quote(ifelse(group_var_val == "Yes", var_name_val/10, var_name_val/20)),
group_var_val = as.name("group_var"),
var_name_val = as.name(var_name))
)
}
# test the function
update_var_2("(Weird) Variable name") %>%
head(n = 20)
這兩個函數應該沒有相同的結果嗎?