R - Get specific cell in CSV from value in another cell?

Viewed 111

If I do this

data %>% filter(primary.name == "Down syndrome" | other.names == "Down syndrome")

I get the whole row of data. But what if I only want the data in one of the cells (ie, the one with the "dx" header)?

I tried this:

data$dx %>% filter(primary.name == "Down syndrome" | other.names == "Down syndrome")

But got this error:

Error in UseMethod("filter_") : 
  no applicable method for 'filter_' applied to an object of class "factor"
1 Answers

We can pull the column after the filter step

library(dplyr)
data %>% 
  filter(primary.name == "Down syndrome" | other.names == "Down syndrome") %>%
  pull(dx)

Or another option is summarise (which can now return more than one row)

data %>%
  summarise(dx = dx[primary.name == "Down syndrome" |
                    other.names == "Down syndrome"]) %>%
  pull(dx)

However, it is better to use filter for understanding the code


If we use

data$dx %>%
    ...

The rhs of %>% only gets the value of that column and there is no way it can access the 'primary.name' or 'other.names' column in the dataset

Related