数据框的内容以特定形式放入列表
Content of data frame into list with specific form
我正在寻找将数据转换为列表格式的特定方法。我想要的最好用示例数据来解释:
library(dplyr)
data <- as.data.frame(cbind(matrix(1:4, 10, 1, byrow=T), matrix(2:6, 10, 1, byrow=T), matrix(2:7, 10, 1, byrow=T))) %>%
dplyr::group_by(V1) %>%
dplyr::arrange(.by_group = TRUE)
data # For emphasis "grouped by" V1
# A tibble: 10 x 3
# Groups: V1 [4]
V1 V2 V3
<int> <int> <int>
1 2 2
1 6 6
1 5 4
2 3 3
2 2 7
2 6 5
3 4 4
3 3 2
4 5 5
4 4 3
目的是获取如下格式的列表,其中V1作为拆分(或组)变量,V2和V3列成为V1的单独子列表:
str(list(list(c(2,6,5),c(2,6,4)), list(c(3,2,6),c(3,7,5)),list(c(4,3),c(4,2)), list(c(5,4),c(5,3))))
List of 4
$ :List of 2
..$ : num [1:3] 2 6 5
..$ : num [1:3] 2 6 4
$ :List of 2
..$ : num [1:3] 3 2 6
..$ : num [1:3] 3 7 5
$ :List of 2
..$ : num [1:2] 4 3
..$ : num [1:2] 4 2
$ :List of 2
..$ : num [1:2] 5 4
..$ : num [1:2] 5 3
如您所见,我在 V1 中获得了与不同值一样多的列表。在每个列表中,属于 V1 特定值的列 V2 和 V3 的条目被定义为单独的列表。
现在我正在寻找一个特定的 "formula" 来为我做这件事。我尝试了 lapply/mapply/split 的各种组合,但到目前为止我没有成功。
我们可以split
将'data'转换为list
library(purrr)
library(dplyr)
lst <- split(data[-1], data[1]) %>%
map(as.list)
或者另一种方法是 nest
,提取 .$data
并转换为 list
lst2 <- data %>%
nest(V2, V3) %>%
.$data %>%
map(as.list)
str(lst2)
#List of 4
# $ :List of 2
# ..$ V2: int [1:3] 2 6 5
# ..$ V3: int [1:3] 2 6 4
# $ :List of 2
# ..$ V2: int [1:3] 3 2 6
# ..$ V3: int [1:3] 3 7 5
# $ :List of 2
# ..$ V2: int [1:2] 4 3
# ..$ V3: int [1:2] 4 2
# $ :List of 2
# ..$ V2: int [1:2] 5 4
# ..$ V3: int [1:2] 5 3
此外,名称 'V2'、'V3' 可以用 unname
删除
lst2 %>%
map(unname) %>%
str
我正在寻找将数据转换为列表格式的特定方法。我想要的最好用示例数据来解释:
library(dplyr)
data <- as.data.frame(cbind(matrix(1:4, 10, 1, byrow=T), matrix(2:6, 10, 1, byrow=T), matrix(2:7, 10, 1, byrow=T))) %>%
dplyr::group_by(V1) %>%
dplyr::arrange(.by_group = TRUE)
data # For emphasis "grouped by" V1
# A tibble: 10 x 3
# Groups: V1 [4]
V1 V2 V3
<int> <int> <int>
1 2 2
1 6 6
1 5 4
2 3 3
2 2 7
2 6 5
3 4 4
3 3 2
4 5 5
4 4 3
目的是获取如下格式的列表,其中V1作为拆分(或组)变量,V2和V3列成为V1的单独子列表:
str(list(list(c(2,6,5),c(2,6,4)), list(c(3,2,6),c(3,7,5)),list(c(4,3),c(4,2)), list(c(5,4),c(5,3))))
List of 4
$ :List of 2
..$ : num [1:3] 2 6 5
..$ : num [1:3] 2 6 4
$ :List of 2
..$ : num [1:3] 3 2 6
..$ : num [1:3] 3 7 5
$ :List of 2
..$ : num [1:2] 4 3
..$ : num [1:2] 4 2
$ :List of 2
..$ : num [1:2] 5 4
..$ : num [1:2] 5 3
如您所见,我在 V1 中获得了与不同值一样多的列表。在每个列表中,属于 V1 特定值的列 V2 和 V3 的条目被定义为单独的列表。
现在我正在寻找一个特定的 "formula" 来为我做这件事。我尝试了 lapply/mapply/split 的各种组合,但到目前为止我没有成功。
我们可以split
将'data'转换为list
library(purrr)
library(dplyr)
lst <- split(data[-1], data[1]) %>%
map(as.list)
或者另一种方法是 nest
,提取 .$data
并转换为 list
lst2 <- data %>%
nest(V2, V3) %>%
.$data %>%
map(as.list)
str(lst2)
#List of 4
# $ :List of 2
# ..$ V2: int [1:3] 2 6 5
# ..$ V3: int [1:3] 2 6 4
# $ :List of 2
# ..$ V2: int [1:3] 3 2 6
# ..$ V3: int [1:3] 3 7 5
# $ :List of 2
# ..$ V2: int [1:2] 4 3
# ..$ V3: int [1:2] 4 2
# $ :List of 2
# ..$ V2: int [1:2] 5 4
# ..$ V3: int [1:2] 5 3
此外,名称 'V2'、'V3' 可以用 unname
lst2 %>%
map(unname) %>%
str