tidyr: using mutate inside a function

落花浮王杯 提交于 2020-01-23 06:47:05

问题


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

回答1:


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

Or another option is mutate_at with 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


来源:https://stackoverflow.com/questions/49576271/tidyr-using-mutate-inside-a-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!