user3375672
user3375672

Reputation: 3768

R: dataframe with unequal row lengths (empty values) into list of rows

df <- data.frame(
  a= c('a',''),
  b= c('b', 'c'), 
  stringsAsFactors = F,
  row.names = c('id1', 'id2')
)

> df
    a b
id1 a b
id2   c

If I consider the second element in column a as empty (value is ''), how can I turn this dataframe into a list l of each row while removing the 'empty' values.

> l
$id1
[1] "a" "b"

$id2
[1] "c"

Upvotes: 1

Views: 24

Answers (1)

akrun
akrun

Reputation: 887501

We can do a split

lapply(split(as.matrix(df), row.names(df)), setdiff, "")
#$id1
#[1] "a" "b"

#$id2
#[1] "c"

Upvotes: 1

Related Questions