noodlez
noodlez

Reputation: 53

Add column with column name as input string

Quick dplyr question here. I'm trying to create a function that takes in any column name and adds the column to the dataframe. For example:

Name               Age 
Misty              4    
Crookshanks        12
Simba              18

Now i want to add the column 'type' via the function at the bottom:

addColumn(myDF, 'Type', 'Cat')

Name               Age       Type
Misty              4         Cat
Crookshanks        12        Cat
Simba              18        Cat

How do I use that function to accept the column string input? Right now it is just writing the column as 'column' instead of 'Type'

addColumn <- function(df, column, value) {

  df <- df %>%
    mutate( column  = value )

  View(df)
}

Upvotes: 3

Views: 191

Answers (2)

davidnortes
davidnortes

Reputation: 932

Just in order to offer an alternative, you could rewrite your function using good old base R as:

addColumn <- function(df, column, value) {
  df[column]<-value
  return(df)
}

Which will give you the same result:

> print(addColumn(myDF,"Type", "Cat"))
         Name Age Type
1       Misty   4  Cat
2 Crookshanks  12  Cat
3       Simba  18  Cat

Without needing to call additional libraries (not even dplyr)

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 389175

You have to use some non-standard evaluation.

library(dplyr)
library(rlang)

addColumn <- function(df, column, value) {
   df %>% mutate(!!column := value )
}

addColumn(myDF, 'Type', 'Cat')

#        Name  Age Type
#1       Misty   4  Cat
#2 Crookshanks  12  Cat
#3       Simba  18  Cat

Upvotes: 2

Related Questions