Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in R Programming by (50.2k points)

The following code is my data-frame and I just want to select the columns into a new data.frame.

library(dplyr)

df = data.frame(

    Manhattan=c(1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0), 

    Brooklyn=c(0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0), 

    The_Bronx=c(1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0), 

    Staten_Island=c(0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0), 

    "2012"=c("P", "P", "P", "P", "P", "P", "P", "P", "P", "P", "Q", "Q", "Q", "Q", "Q", "Q", "Q", "Q", "Q"), 

    "2013"=c("P", "P", "P", "P", "P", "P", "P", "P", "Q", "Q", "P", "P", "P", "P", "Q", "Q", "Q", "Q", "Q"), 

    "2014"=c("P", "P", "P", "Q", "Q", "P", "P", "Q", "Q", "Q", "Q", "Q", "P", "Q", "P", "P", "P", "Q", "Q"), 

    "2015"=c("P", "P", "P", "P", "P", "Q", "Q", "Q", "P", "Q", "P", "P", "Q", "Q", "Q", "Q", "Q", "Q", "Q"), check.names=FALSE)

df2 <- subset(df, select = c("Manhattan", "Queens", "The_Bronx"))

But the above code gives me the following error:

Error in [.data.frame`(x, r, vars, drop = drop) : 

   undefined columns selected

I know that the "Queens" column is missing from the data-frame. How can I can override the error, so that R proceeds to create df2 with columns "Manhattan" and "The_Bronx" only?

1 Answer

0 votes
by (108k points)

In R programming, you can take help of the intersect() function as it will help you to select only the names which are present in the data-frame:

cols <- c("Manhattan", "Queens", "The_Bronx")

subset(df, select = intersect(names(df), cols))

#   Manhattan The_Bronx

#1          1         1

#2          1         1

#3          0         0

#4          1         0

#5          1         0

#6          1         0

#7          1         0

#8          0         0

#...

#....

Or if you want to use a package then you can have any_of() which is being provided by the dplyr package :

library(dplyr)

df %>% select(tidyselect::any_of(cols))

Browse Categories

...