The question is very straightforward. I am using the haven
package, which creates a custom class called haven_labelled
when importing data from Stata into R (which has the benefit of displaying labels in R). I would like to select columns which have this custom class (or any other custom class).
With the standard classes one would use is.numeric
, is.factor
etc.
For example: df <- Filter(is.numeric, df)
.
Many other ways of doing this can be found here.
I have tried substituting these examples with class=="haven_labelled"
.
For example: df <- Filter(class=="haven_labelled", df)
,
but that does not work. It gives the error:
Error in class == "haven_labelled" :
comparison (1) is possible only for atomic and list types
Any ideas?
EDIT:
When trying H 1's solution, I figured out two things which might be important to anyone else using the haven package.
labelled
in addition to another class). Hence selection based on labelled just returns the full dataset.You can create a simple function to test if something is of class "haven_labelled" and then use it to subset your data. For example:
is.haven <- function(x) "haven_labelled" %in% class(x)
Filter(is.haven, df)
or
df[sapply(df, is.haven)]
or
dplyr::select_if(df, is.haven)