tidyr:在函数内使用 mutate [英] tidyr: using mutate inside a function
问题描述
我想使用 tidyverse 中的 mutate 函数基于旧列创建一个新列,仅使用数据框和字符串作为输入,这些字符串代表列标题.
I'd like to use mutate function from the tidyverse to create a new column based on the old column using only a data frame and strings, which represent column headers, as inputs.
我可以在不使用 tidyverse 的情况下使其工作(请参阅下面的函数 f),但我想使用 tidyverse 使其工作(请参阅下面的函数 f.tidy)
I can get this to work without using the tidyverse (see function f below), but I'd like to get it to work using the tidyverse (see function f.tidy below)
有人可以发布使用从内部函数调用的 mutate 添加此列的解决方案吗?
Can someone please post a solution for adding this column using mutate called from a inside function?
df <- data.frame('test' = 1:3, 'tcy' = 4:6)
# test tcy
# 1 4
# 2 5
# 3 6
f.tidy <- function(df, old.col, new.col) {
df.rv <- df %>%
mutate(new.col = .data$old.col + 1)
return(df.rv)
}
f <- function(df, old.col, new.col) {
df.rv <- df
df.rv[, new.col] <- df.rv[, old.col] + 1
return(df.rv)
}
old.col <- 'tcy'
new.col <- 'dan'
f.tidy(df = df, old.col = old.col, new.col = new.col)
# Evaluation error: Column 'old.col': not found in data
f(df = df, old.col = old.col, new.col = new.col)
# Produces Desired Output:
# test tcy dan
# 1 4 5
# 2 5 6
# 3 6 7
推荐答案
我们可以使用 rlang
将其转换为符号,然后使用 !!
We could use rlang
to convert it to symbol and then evaluate with !!
f.tidy <- function(df, old.col, new.col) {
df %>%
mutate(!! (new.col) := !!rlang::sym(old.col) + 1)
}
f.tidy(df = df, old.col = old.col, new.col = new.col)
# test tcy dan
#1 1 4 5
#2 2 5 6
#3 3 6 7
<小时>
或者另一个选项是 mutate_at
和 rename_at
f.tidy <- function(df, old.col, new.col) {
df %>%
mutate_at(vars(old.col), funs(new = .+ 1)) %>%
rename_at(vars(matches("new")), ~ new.col)
}
f.tidy(df = df, old.col = old.col, new.col = new.col)
# test tcy dan
#1 1 4 5
#2 2 5 6
#3 3 6 7
这篇关于tidyr:在函数内使用 mutate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!