user11740857
user11740857

Reputation: 480

Creating a new class in R dataframe

I am in need of creating a new class in R dataframe. Example,

asd <- data.frame(a = c("A", "B"), b = c("D","S"))
class(asd$b) <- "New" 

As you see, I have a created a new class "New". But when I do below operation, I do not get a

asd %>% select_if(is.New) 
Error in is_logical(.predicate) : object 'is.New' not found

Expected output

   b
1  D
2  S

Upvotes: 1

Views: 71

Answers (2)

akrun
akrun

Reputation: 886998

We may use select with where

library(dplyr)
asd %>%
    select(where(~ is(., "New")))

-output

 b
1 D
2 S

Upvotes: 0

MrFlick
MrFlick

Reputation: 206197

Just because you create a class of "New" doesn't mean a function with the name is.New was also created. The generic form of is() takes a class name as a character value. You would use it like

asd %>% select_if(~is(., "New"))

And if you wanted to create is.New you could do

is.New <- function(x) is(x, "New")

asd %>% select_if(is.New) 

Upvotes: 3

Related Questions