[英]R: select every n rows of a data frame and put each n rows into element of a list
Like the title suggested, I'd like to take every n rows of a dataframe and put each block into a list.就像建议的标题一样,我想每 n 行 dataframe 并将每个块放入一个列表中。
I have some path level data stacked in a dataframe and want to separate each path into element of a list.我有一些路径级别的数据堆叠在 dataframe 中,并且希望将每个路径分成列表的元素。
The data I have:我拥有的数据:
df3 <- as.data.frame(matrix(c(1,1,1,2,2,2,3,3,3,1,2,3,1,2,3,1,2,3,5,6,7,4,6,5,6,7,6), nrow=9, ncol=3))
names(df3) <- c("path","month", "data")
print(df3)
path month data
1 1 1 5
2 1 2 6
3 1 3 7
4 2 1 4
5 2 2 6
6 2 3 5
7 3 1 6
8 3 2 7
9 3 3 6
Desired result:期望的结果:
myList <- list()
myList[[1]]<- as.data.frame(matrix(c(1,1,1,1,2,3,5,6,7), nrow=3, ncol=3))
myList[[2]]<- as.data.frame(matrix(c(2,2,2,1,2,3,4,6,5), nrow=3, ncol=3))
myList[[3]]<- as.data.frame(matrix(c(3,3,3,1,2,3,6,7,6), nrow=3, ncol=3))
print(myList)
> print(myList)
[[1]]
V1 V2 V3
1 1 1 5
2 1 2 6
3 1 3 7
[[2]]
V1 V2 V3
1 2 1 4
2 2 2 6
3 2 3 5
[[3]]
V1 V2 V3
1 3 1 6
2 3 2 7
3 3 3 6
Can be done using可以使用
lapply(seq(1,9,3),function(x) df3[x:(x+2),])
[[1]]
V1 V2
1 1 5
2 1 6
3 1 7
[[2]]
V1 V2
4 2 4
5 2 6
6 2 5
[[3]]
V1 V2
7 3 6
8 3 7
9 3 6
Somhow, the data you display and what is contained by df3
is not the same.怎么看,你显示的数据和
df3
包含的数据是不一样的。 Still, this works for both.不过,这对两者都有效。
We can use split
我们可以使用
split
lst1 <- split(df3, df3$path)
lst1
#$`1`
# path month data
#1 1 1 5
#2 1 2 6
#3 1 3 7
#$`2`
# path month data
#4 2 1 4
#5 2 2 6
#6 2 3 5
#$`3`
# path month data
#7 3 1 6
#8 3 2 7
#9 3 3 6
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.