Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A function that adds new columns to a dataframe

Tags:

r

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.

like image 983
user32259 Avatar asked Dec 11 '22 18:12

user32259


1 Answers

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
like image 69
thelatemail Avatar answered Jan 04 '23 20:01

thelatemail