[R] Adding collumn to existing data frame

Ralf B ralf.bierig at gmail.com
Wed Aug 4 02:32:58 CEST 2010


Hi experts,

I am trying to write a very flexible method that allows me to add a
new column to an existing data frame. This is what I have so far:

add.column <- function(df, new.col, name) {
	n.row <- dim(df)[1]
	length(new.col) <- n.row
	names(new.col) <- name
	return(cbind(df, new.col))
}

df <- NULL
df <- data.frame(a=c(1,2,3))
df
# corect: added NA to new collumn
df <- add.column(df,c(1,2),'myNewColumn2')
df
# problem: not added, data frame should be extended with NAs
add.column(df,c(1,2,3,4),'myNewColumn3')
df


However, there are two problems:

1) The column name is not renamed accurately but always set to
'new.col' . Surely this could be done outside the function, but it
would be better if its self contained.
2) It does not work for cases where new.col is longer than the length
of the data frame. In such cases, I would like to add NA's to the data
frame if it has less rows.

Any ideas to to solve this?

Ralf



More information about the R-help mailing list