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.
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)
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