Adding and removing columns from a data frame

Problem

You want to add or remove columns from a data frame.

Solution

There are many different ways of adding and removing columns from a data frame.

  1. data <- read.table(header=TRUE, text='
  2. id weight
  3. 1 20
  4. 2 27
  5. 3 24
  6. ')
  7. # Ways to add a column
  8. data$size <- c("small", "large", "medium")
  9. data[["size"]] <- c("small", "large", "medium")
  10. data[,"size"] <- c("small", "large", "medium")
  11. data$size <- 0 # Use the same value (0) for all rows
  12. # Ways to remove the column
  13. data$size <- NULL
  14. data[["size"]] <- NULL
  15. data[,"size"] <- NULL
  16. data[[3]] <- NULL
  17. data[,3] <- NULL
  18. data <- subset(data, select=-size)