Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to subset a Data frame column wise using column names? [duplicate]

Tags:

dataframe

r

I have created a data frame named z.

  a = c(1,1,1);
  b = c(2,2,2);
  c = c(3,3,3);
  d = c(4,4,4);
  z = data.frame(a,b,c,d);

I want to remove column c and d from data frame z.

I tried this code

p = subset(z , colnames(z) == c('a' , 'b'))

But i am getting this result

a   b   c   d
1   2   3   4   
1   2   3   4 

What changes should i make in this command to remove column c and d from z.

like image 359
Nikhil Singhal Avatar asked Aug 23 '17 17:08

Nikhil Singhal


People also ask

How do you subset columns in a data frame?

Selecting columns is also known as selecting a subset of columns from the dataframe. You can select columns from Pandas Dataframe using the df. loc[:,'column_name'] statement.

How do I subset a DataFrame by a column name in R?

How to subset the data frame (DataFrame) by column value and name in R? By using R base df[] notation, or subset() you can easily subset the R Data Frame (data. frame) by column value or by column name.

How do I find duplicates in a column in a data frame?

Code 1: Find duplicate columns in a DataFrame. To find duplicate columns we need to iterate through all columns of a DataFrame and for each and every column it will search if any other column exists in DataFrame with the same contents already. If yes then that column name will be stored in the duplicate column set.


1 Answers

We can use the following to specify which columns to select by names.

z[, c("a", "b")]

This also works.

z[c("a", "b")]

Or we can use the following to first specify which columns to remove in a vector, and then select the columns not in that vector.

cols_remove <- c("c", "d")
z[, !(colnames(z) %in% cols_remove)]
like image 76
www Avatar answered Nov 15 '22 01:11

www