icedcoffee
icedcoffee

Reputation: 1015

How to filter values in a list within a dataframe in R?

I have a dataframe, df:

df <- structure(list(id = c("id1", "id2", "id3", 
"id4"), type = c("blue", "blue", "brown", "blue"
), value = list(
    value1 = "cat", value2 = character(0), 
    value3 = "dog", value4 = "fish")), row.names = 1:4, class = "data.frame")

> df
   id  type value
1 id1  blue   cat
2 id2  blue      
3 id3 brown   dog
4 id4  blue  fish

The third column, value, is a list. I want to be able to filter out any rows in the dataframe where entries in that column that don't have any characters (ie. the second row).

I've tried this:

df <- filter(df, value != "")

and this

df <- filter(df, nchar(value) != 0)

But it doesn't have any effect on the data frame. What is the correct way to do this so my data frame looks like this:

> df
   id  type value
1 id1  blue   cat
3 id3 brown   dog
4 id4  blue  fish

Upvotes: 0

Views: 274

Answers (4)

Marcos P&#233;rez
Marcos P&#233;rez

Reputation: 1250

Try this:

df <- filter(df, !sapply(df$value,function(x) identical(x,character(0))) )

Upvotes: 1

akrun
akrun

Reputation: 887108

An option with tidyverse

library(dplyr)
library(purrr)
df %>%
     filter(map_int(value, length) > 0)
#   id  type value
#1 id1  blue   cat
#2 id3 brown   dog
#3 id4  blue  fish

Upvotes: 1

Qi Yin
Qi Yin

Reputation: 159

here is my approach

idx <- lapply(df$value, length)
filter(df, idx > 0)

  id  type value
1 id1  blue   cat
2 id3 brown   dog
3 id4  blue  fish

Upvotes: 1

Gregor Thomas
Gregor Thomas

Reputation: 145775

The lengths() function is perfect here - it gives the length of each element of a list. You want all the rows where value has non-zero length:

df[lengths(df$value) > 0, ]
#    id  type value
# 1 id1  blue   cat
# 3 id3 brown   dog
# 4 id4  blue  fish

Upvotes: 2

Related Questions