user32259
user32259

Reputation: 1143

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.

Upvotes: 4

Views: 468

Answers (3)

David
David

Reputation: 775

If you know the name of the new column, you can do this:

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

Upvotes: 0

thelatemail
thelatemail

Reputation: 93803

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

Upvotes: 11

adibender
adibender

Reputation: 7568

f = function(df, col.name, col.value){
  df[[col.name]] <- col.value
  print(df)
 }

If you want to accommodate @flodel's and @theodore's comments you could use something like:

f <- function(df, col.name, col.value, overwrite = FALSE){

    if ( col.name %in colnames(df) ) {
        if ( overwrite ) {
            warning(paste("column", col.name, "overwritten!"))
        } else {
            stop(paste("column", col.name, "already exists!"))
        }
    }

    df[[col.name]] <- col.value 
    return(df)
}

Upvotes: 3

Related Questions