Sati Sati - 3 years ago 187
R Question

R - alter list structure

I have some textual data which presents itself in the following format after being read into R:

> lst <- list('A', c("", 'aa'), 'bb', 'cc', 'B', c("", 'aa'), 'bb', 'cc', 'dd')

[[1]]
[1] "A"

[[2]]
[1] "" "aa"

[[3]]
[1] "bb"

[[4]]
[1] "cc"

[[5]]
[1] "B"

[[6]]
[1] "" "aa"

[[7]]
[1] "bb"

[[8]]
[1] "cc"

[[9]]
[1] "dd"


Is there an easy way to change the structure of this list using "" as an indicator, so that the item immediately before "" becomes a list heading?

lst2 <- list(A=c('aa', 'bb', 'cc'), B=c('aa', 'bb', 'cc', 'dd'))

$A
[1] "aa" "bb" "cc"

$B
[1] "aa" "bb" "cc" "dd"

Answer Source

We could do

v1 <- unlist(lst)
i1 <- cumsum(c(!nzchar(v1)[-1], FALSE))
lst2 <- tapply(v1, i1, FUN = function(x) x[-(1:2)])
names(lst2) <-   tapply(v1, i1, FUN = head, 1)
lst2
#$A
#[1] "aa" "bb" "cc"

#$B
#[1] "aa" "bb" "cc" "dd"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download