Add an empty row and column to an R data frame

Several years ago I was stumped trying to figure out how to create an empty R data frame and populate its rows and columns with irregular data slurped in using scan(). My solution was pretty ugly, involving a lot of trial-and-error, finding each special case and hard-coding its exception. Faced with the problem again I decided to find a better way. The new solution:

# with an existing data.frame called “data”…

# create a one-row matrix the same length as data

temprow <- matrix(c(rep.int(NA,length(data))),nrow=1,ncol=length(data))

# make it a data.frame and give cols the same names as data

newrow <- data.frame(temprow)
colnames(newrow) <- colnames(data)

# rbind the empty row to data

data <- rbind(data,newrow)

# with a previously-defined character object containing the colname
# (“newColName”), add the empty column to the data frame and populate

data[,newColName] <- NA
data[nrow(data),newColName] <- “newValue”
Advertisements
This entry was posted in data munging, R and tagged , , , , . Bookmark the permalink.