user3375672 user3375672 - 1 month ago 6
R Question

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"

Answer

We can do a split

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

#$id2
#[1] "c"
Comments