+3 votes
in Programming Languages by (26.1k 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 (33.7k 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)]

df

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

+2 votes
1 answer
+5 votes
1 answer
+5 votes
1 answer
+5 votes
1 answer
asked Jul 6, 2021 in Programming Languages by kush (26.1k points)

...