Ton Van Voorden
Ton Van Voorden

Reputation: 1

Adding a new column to a dataframe. Problems with creating the right function. Second input parameter is not recognized as a variable

already thank you for helping me.

add_empty_column <- function(a,b) {
  a$b <-0
  return(a)
}

dataframe1$newcolumn <- 0 is creating a new column with the name newcolumn (everywhere 0's)

Why is this not working if I use the above function with add_empty_column(dataframe1,newcolumn)

Thank you already for your reply, struggling for hours now.....

Upvotes: 0

Views: 41

Answers (3)

Duck
Duck

Reputation: 39613

One option using rlang and dplyr could be this (I took data from @AllanCameron):

library(dplyr)
#Data
df <- data.frame(Start = c(5, 15, 22), End = c(10, 21, 38))
#Function
create.colum <- function(x,y)
{
  x %>% mutate(!!rlang::enquo(y):=0) -> x
  return(x)
}
#Apply
create.colum(df,variable)

Output:

  Start End variable
1     5  10        0
2    15  21        0
3    22  38        0

Or if you want to create directly the new variable, you can use this (credits @AllanCameron):

#Code 2
df <- df %>% mutate(variable=0)

Output:

  Start End variable
1     5  10        0
2    15  21        0
3    22  38        0

Upvotes: 1

Allan Cameron
Allan Cameron

Reputation: 174536

If you want your function to work as you expect, you need to use deparse(substitute(b)), and use the bracket operator instead of the $ operator:

add_empty_column <- function(a, b) {
  a[deparse(substitute(b))] <- 0
  return(a)
}

So for example, if we have this data frame:

df <- data.frame(Start = c(5, 15, 22), End = c(10, 21, 38))
                    
df
#>   Start End
#> 1     5  10
#> 2    15  21
#> 3    22  38

We can do:

add_empty_column(df, value)
#>   Start End value
#> 1     5  10     0
#> 2    15  21     0
#> 3    22  38     0

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 389275

Don't use $ when passing column name as variable. Use [[ instead.

add_empty_column <- function(a,b) { a[[b]] <-0;return(a) }

Now pass name of the new column as character.

df <- data.frame(a = 1:5)
df <- add_empty_column(df, 'newcolumn')
df
#  a newcolumn
#1 1         0
#2 2         0
#3 3         0
#4 4         0
#5 5         0

Upvotes: 1

Related Questions