Creating function(data, x) with mutate(x = x*2) in it, does not work

Viewed 39
library(dplyr)

func <- function(data, col){
  data <- data %>%
    mutate(col = {{col}}*2)
  return(data)
}

df <- data.frame(x = c(1:8), y = c("hello", "world", "sun", "winter"))

func(df, x)
  x      y col
1 1  hello   2
2 2  world   4
3 3    sun   6
4 4 winter   8
5 5  hello  10
6 6  world  12
7 7    sun  14
8 8 winter  16

I want the x column to be updated:

 x      y
1  2  hello
2  4  world
3  6    sun
4  8 winter
5 10  hello
6 12  world
7 14    sun
8 16 winter

I tried several things with no success, does anybody have any suggestions? Thanks in advance!

3 Answers

We need the assignment (:=) operator

func <- function(data, col){
data %>%
     mutate({{col}} := {{col}}*2)

  }

func(df, x)

-output

#    x      y
#1  2  hello
#2  4  world
#3  6    sun
#4  8 winter
#5 10  hello
#6 12  world
#7 14    sun
#8 16 winter

This should do it.

library(dplyr)

df <- data.frame(x = c(1:8), y = c("hello", "world", "sun", "winter"))

func(df, x)

func <- function(data, x){
  data <- data %>%
    mutate(x = {{x}}*2)
  return(data)
}

I did not know about this double curly braces. I did some digging. Turns out, you have to put curly-curly around the column you're mutating. Otherwise it will create, a new column.

library(dplyr)

func <- function(data, col){
  data <- data %>%
    mutate({{col}} = {{col}}*2)
  return(data)
}

df <- data.frame(x = c(1:8), y = c("hello", "world", "sun", "winter"))

func(df, x)

output:
   x      y
1  2  hello
2  4  world
3  6    sun
4  8 winter
5 10  hello
6 12  world
7 14    sun
8 16 winter
Related