Priit Mets
Priit Mets

Reputation: 495

How make R ignore undefined columns selected error message in cbind()?

I have a dataframe A, and want to merge a column that exists in A with ones that do not exist in A. I want to make cbind ignore those columns that does not exist and cbind() only existing ones. Something similar to cbind(A$Key.Name,A$Dummy1,A$Dummy2), however preserving dataframe class of the data with the column names.

A<-fromJSON('[{"Key":{"Name":"Victor","ID":61426},"Type":"Unknown","Domain":"Cooking"  }]',
            flatten = T)

names(A)
cbind(A["Key.Name"],A["Dummy1"],A["Dummy2"])

Upvotes: 0

Views: 450

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388907

Use intersect to select only those columns that are present in the data.

cols_to_select <- c('Key.Name', 'Dummy1', 'Dummy2')
result <- A[intersect(names(A), cols_to_select)]

In dplyr you can use any_of :

library(dplyr)
A %>% select(any_of(cols_to_select))

Upvotes: 2

Related Questions