Ari Monger
Ari Monger

Reputation: 71

R Nesting Formulas

I am trying to understand the syntax of R and having difficulty when we nest formulas.

In this case, I am trying to:

  1. select everything in column "Y" that is equal to one
  2. then give me unique values in column "X" when #1 is true.

I know how to do this in two steps but not in a nested format.

Thank you

subset(data, Y == "1") %>%
unique("X")

Upvotes: 0

Views: 93

Answers (2)

user2554330
user2554330

Reputation: 44977

You can do it using magrittr pipes using

subset(mtcars, carb == 1) %$% gear %>% unique()

and with base pipes or magrittr pipes using

subset(mtcars, carb == 1)$gear |> unique()

or

subset(mtcars, carb == 1)$gear %>% unique()

Upvotes: 1

h45
h45

Reputation: 246

If you do not mind using data.table library, it is not necessary to nest. For example, using the mtcars dataset, returning the unique value of column cyl when column carb equals 1 is as follows:

library(data.table)

mtcars

data.table(mtcars)[carb == 1, unique(cyl)]

Upvotes: 1

Related Questions