Reputation: 660
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
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
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