Zhaochen He
Zhaochen He

Reputation: 660

filtering rows in a datatable or dataframe based a column that happens to be a list

I would like to filter this data table, but the column I want to filter by is a list.

#example data
time= c(1, 2, 3, 4)
conditions = list('rain', 'rain', c('rain', 'sleet'), 'rain')
data = data.table(date, conditions)
print(data)

   time conditions
1:    1       rain
2:    2       rain
3:    3 rain,sleet
4:    4       rain

The normal commands don't seem to work:

# Data.Table
data[conditions == c('rain', 'sleet')] # Gives error
# dplyr
filter(data,conditions == c('rain', 'sleet')) # Doesn't return desired result

Please advise.

Upvotes: 1

Views: 46

Answers (2)

acylam
acylam

Reputation: 18681

We can use identical:

data[sapply(conditions, identical, c('rain', 'sleet')), ] 

or with tidyverse:

library(tidyverse)

data %>%
  filter(map_lgl(conditions, identical, c('rain', 'sleet')))

Output:

   date conditions
1:    3 rain,sleet

Upvotes: 2

D.sen
D.sen

Reputation: 922

You could use the purrr package and pass the identical function.

library(dplyr)    
library(purrr)

data %>%
  filter(map_lgl(conditions, ~identical(c('rain','sleet'), .))) 

> time  conditions
>    3  rain, sleet

Upvotes: 1

Related Questions