How do I insert a row into a data.frame?

Suppose you have an object data.frame

:

foo <- data.frame(ID=LETTERS[1:10], 
          blah=1:10, foo=1:10, 
          row.names=letters[1:10])

      

I want to insert a string at an arbitrary position in a data.frame. Maybe like the first row, maybe like the last. Nevertheless,

  • the data types of the resulting data.frame must be identical to the data types in the original data frame
  • string names must be stored

I tried to do it with rbind and ended up writing a long function that still doesn't work as expected. Isn't there an elegant way to do this?

I am including my function below, but I don't think it is good.

df.insert <- function(df, i, row, rowname) {
  if(is.null(df)) return(df)
  if(!is.list(row)) stop("row must be a list")
  if(!all(names(rowname) %in% colnames(df)))
    stop("df.insert error: all names of rowname must be in colnames of df")

  rnames <- rownames(df)
  nr <- nrow(df)
  if(i > nr) i <- nr

  for(n in colnames(df))
    if(!n %in% names(row)) row[[n]] <- NA

  if(nr == 0)      {
    ret <- data.frame(row)
    rownames(ret) <- rowname
  } else if(i == 0) { 
    ret <- rbind(row, df, make.row.names=FALSE)
    rownames(ret) <- c(rowname, rnames)
  } else if(i == nr) {
    ret <- rbind(df, row, make.row.names=FALSE)
    rownames(ret) <- c(rnames, rowname)
  } else { 
    ret <- rbind(df[1:i,], row, df[(i+1):nr,], make.row.names=FALSE)
    rownames(ret) <- c(rnames[1:i], rowname, rnames[(i+1):nr])
  }
  return(ret)
}

      

EDIT: The answers to this question do not handle two things: (i) adding a string to the end of the dataframe and (ii) dealing with string names. However, they provide another elegant solution that I am working on.

+3


source to share





All Articles