开发者

transform vector into list

开发者 https://www.devze.com 2023-02-14 23:15 出处:网络
I have vector: c(\"A\",\"1\",\"2\",\"3\",\"B\",\"4\",\"5\",\"D\",\"6\",\"7\",\"8\",\"9\",\"10\") I would like to transform this vector into list: list(A=c(1,2,3),B=c(4,5),...)

I have vector: c("A","1","2","3","B","4","5","D","6","7","8","9","10") I would like to transform this vector into list: list(A=c(1,2,3),B=c(4,5),...) Letters from vector are names in list of vectors. Vectors a开发者_JS百科re from number blocks between letters.


Here's one way. Nothing fancy, but it gets the job done.

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]))
0

精彩评论

暂无评论...
验证码 换一张
取 消