将矢量转换为列表

时间:2011-03-02 22:07:03

标签: r

我有矢量:c("A","1","2","3","B","4","5","D","6","7","8","9","10") 我想将此向量转换为列表:list(A=c(1,2,3),B=c(4,5),...) 来自矢量的字母是矢量列表中的名称。矢量来自字母之间的数字块。

1 个答案:

答案 0 :(得分:22)

这是一种方式。没什么好看的,但它完成了工作。

x <- c("A","1","2","3","B","4","5","D","6","7","8","9","10")
y <- cumsum( grepl("[[:alpha:]]", x) )
z <- list()
for(i in unique(y)) z[[x[y==i][1]]] <- as.numeric(x[y==i][-1])
z
# $A
# [1] 1 2 3
#
# $B
# [1] 4 5
#
# $D
# [1]  6  7  8  9 10

# UPDATE: Trying to be a bit more "fancy"
a <- grepl("[[:alpha:]]", x)
b <- factor(cumsum(a), labels=x[a])
c <- lapply(split(x,b), function(x) as.numeric(x[-1]))