Thursday, 12 March 2015

Data Manipulation: Deleting columns in R

Adding or deleting columns are one of the most basic tasks that need to be performed. In R, we can do so using multiple techniques. The trade off between the methods can be truly appreciated only the operations are performed on large datasets i.e. speed of operation becomes visible.

Nevertheless, this post is here to give you a simple guide on different ways to delete columns in R.

Let us first create a data frame.

Code
year <- c(2001,2002,2003,2004)
> name <- c("A","B","C","D")
> price <- c(12,32,42,53)
> volume <- c(32,42,53,64)
> sales <- data.frame(year,name,price,volume)
> class(sales)
[1] "data.frame"








1. First method

Use the subset command on the data frame
> sales <- subset(sales, select = -c(name,volume))
> class(sales)
2. Second Method
sales[1] <- NULL
sales[1:3] <- list(NULL) #the list needs to be used here