gpt4 book ai didi

r - 如何对 data.frames 列表进行子集化?

转载 作者:行者123 更新时间:2023-12-05 04:31:42 25 4
gpt4 key购买 nike

我有一个 data.frames 列表,想对一部分数据帧进行子集化。在这种情况下,我想将 mainlistsublist1 和 sublist2 中的 rainfallyield 子集并创建一个新的名为 mainlist_new 的列表。

但是我遇到了这个错误Error in mainlist[[1]][[, 2:3]] : incorrect number of subscripts

有什么想法和想法吗?

这里是代码和创建的数据

> df1 <- data.frame(station = c("MADA1", "MADA2", "MADA3", "MADA4", "MADA5"),
+ rainfall = c(0, 5, 10, 15, 20),
+ yield = c(2000, 3000, 4000, 5000, 6000))
> df2 <- df1
> df3 <- df1
>
> list_1 <- list(df1, df2, df3)
>
> list_2 <- list(df1, df2, df3)
>
> mainlist <- list(list_1, list_2)
> names(mainlist) <- c("sublist1", 'sublist2')
> names(mainlist[[1]]) <- c("station", "rainfall", "yield")
> names(mainlist[[2]]) <- c("station", "rainfall", "yield")
>
> names(mainlist)
[1] "sublist1" "sublist2"
> names(mainlist[[1]])
[1] "station" "rainfall" "yield"
>
> # subset `rainfall` and `yield` is sublist1 and sublist2 and create a a new list
> mainlist_new <- list()
> mainlist_new[[1]] <- mainlist[[1]][[,2:3]]
Error in mainlist[[1]][[, 2:3]] : incorrect number of subscripts
> mainlist_new[[2]] <- mainlist[[2]][[,2:3]]
Error in mainlist[[2]][[, 2:3]] : incorrect number of subscripts
>

最佳答案

如果我们想根据名称对 list 元素进行子集化

mainlist_new <- lapply(mainlist, `[`, c("rainfall", "yield"))

-输出

> str(mainlist_new)
List of 2
$ :List of 2
..$ rainfall:'data.frame': 5 obs. of 3 variables:
.. ..$ station : chr [1:5] "MADA1" "MADA2" "MADA3" "MADA4" ...
.. ..$ rainfall: num [1:5] 0 5 10 15 20
.. ..$ yield : num [1:5] 2000 3000 4000 5000 6000
..$ yield :'data.frame': 5 obs. of 3 variables:
.. ..$ station : chr [1:5] "MADA1" "MADA2" "MADA3" "MADA4" ...
.. ..$ rainfall: num [1:5] 0 5 10 15 20
.. ..$ yield : num [1:5] 2000 3000 4000 5000 6000
$ :List of 2
..$ rainfall:'data.frame': 5 obs. of 3 variables:
.. ..$ station : chr [1:5] "MADA1" "MADA2" "MADA3" "MADA4" ...
.. ..$ rainfall: num [1:5] 0 5 10 15 20
.. ..$ yield : num [1:5] 2000 3000 4000 5000 6000
..$ yield :'data.frame': 5 obs. of 3 variables:
.. ..$ station : chr [1:5] "MADA1" "MADA2" "MADA3" "MADA4" ...
.. ..$ rainfall: num [1:5] 0 5 10 15 20
.. ..$ yield : num [1:5] 2000 3000 4000 5000 6000

关于r - 如何对 data.frames 列表进行子集化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71801655/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com