user32259 user32259 - 4 months ago 10
R Question

A function that adds new columns to a dataframe

I need a function which adds a new column (with constant values) to a dataframe

df
. My attempt so far is this:

f = function(df, col.name, col.value){
df$col.name = col.value
print(df)
}


A typical input would be:

f(df, "New column", NA)


This would give me a new column with value NA, however, it would be named
col.name
.

Any help much appreciated.

Answer

R has in-built functions for this sort of thing, namely $<- for assigning a single column of data.

> test <- data.frame(a=1:3,b=4:6)

> test
  a b
1 1 4
2 2 5
3 3 6

> `$<-`(test,"new_column",NA)
  a b new_column
1 1 4         NA
2 2 5         NA
3 3 6         NA

As @MatthewLundberg says in the comment below, you could assign this to your new function if you want to avoid the funky function name:

> f <- `$<-`
> f(test,"new_column",NA)
  a b new_column
1 1 4         NA
2 2 5         NA
3 3 6         NA