R-变更清单结构 [英] R - alter list structure
问题描述
我有一些文本数据,在读入R后会以以下格式显示:
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"
推荐答案
我们可以将list
list
unlist
转换为vector
('v1'),然后根据空字符串的位置创建分组索引( !nzchar(v1)
),删除第一个元素并在末尾附加FALSE,以获取累积总和,以便该组从出现空字符串之前的位置开始.然后,在tapply
中使用它,删除向量的第一个元素,然后按操作使用group by来获取向量的第一个元素,以命名"lst2"
We could unlist
the list
to a vector
('v1'), then create a grouping index based on the position of empty strings (!nzchar(v1)
), removed the first element and append FALSE at the end, get the cumulative sum so that the group starts at the position before the occurence of empty string. Then, we use that in tapply
, remove the first elements of the vector and use a group by operation to get the first element of the vector for naming the 'lst2'
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"
这篇关于R-变更清单结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!