+3 votes
in Programming Languages by (39.3k points)
I want to remove a couple of columns from a given dataframe. What R function should I use for it?

1 Answer

+3 votes
by (63.4k points)
selected by
Best answer

You can drop columns from an R dataframe without using any R function. You need to find the columns you want to keep and then use them to slice the dataframe.

Here is an example. I am using set difference to find the columns that I want to keep in the resulting dataframe.

df <- data.frame(x=c(10,20,30,40), y=c(1,2,3,4),z=c(11,12,13,14), w=c(11,22,33,44))

cols <- colnames(df)

cols_to_del = c("y", "w")

df <- df[setdiff(cols, cols_to_del)]


Now df will have just 2 columns: x and z.

> df

   x  z

1 10 11

2 20 12

3 30 13

4 40 14 

Related questions

+1 vote
1 answer
+2 votes
1 answer
+5 votes
1 answer