[英]Create nested list from csv in R
我有一個 CSV 文件,用於在 R 中創建列表。
> list <- read.csv("/Users/shrik/Documents/V\ Test/PEdit/main/word_list.csv", header = F)
> list
V1 V2 V3 V4
1 the 0.27000 2.91000 1.000000
2 well 2.91000 3.39000 1.000000
3 well 3.96000 4.35000 1.000000
4 keeping 4.53000 4.95000 1.000000
5 yourself 4.95000 5.43000 1.000000
我想創建一個嵌套列表,而不是上面的列表,其中 V2、V3、V4 值將位於每個 V1 元素的子列表中。 一些善良的靈魂可以幫助嗎?
用 function 來命名 object 通常不是好的做法(這里, list
也是一個函數); 您可以使用例如list1
。
library(tidyverse)
list1 %>%
group_by(V1) %>%
summarise(across(V2:V4, list)) %>%
transpose()
如果要保持列順序,則必須將變量轉換為因子,然后由於purrr::transpose
將因子強制轉換為數字,因此必須使用pmap(list)
。
list1 %>%
group_by(V1 = as_factor(V1)) %>%
summarise(across(V2:V4, list)) %>%
pmap(list)
output
[[1]]
[[1]]$V1
[1] the
Levels: the well keeping yourself
[[1]]$V2
[1] 0.27
[[1]]$V3
[1] 2.91
[[1]]$V4
[1] 1
[[2]]
[[2]]$V1
[1] well
Levels: the well keeping yourself
[[2]]$V2
[1] 2.91 3.96
[[2]]$V3
[1] 3.39 4.35
[[2]]$V4
[1] 1 1
[[3]]
[[3]]$V1
[1] keeping
Levels: the well keeping yourself
[[3]]$V2
[1] 4.53
[[3]]$V3
[1] 4.95
[[3]]$V4
[1] 1
[[4]]
[[4]]$V1
[1] yourself
Levels: the well keeping yourself
[[4]]$V2
[1] 4.95
[[4]]$V3
[1] 5.43
[[4]]$V4
[1] 1
數據
list1 <- read.table(header = T, text = " V1 V2 V3 V4
1 the 0.27000 2.91000 1.000000
2 well 2.91000 3.39000 1.000000
3 well 3.96000 4.35000 1.000000
4 keeping 4.53000 4.95000 1.000000
5 yourself 4.95000 5.43000 1.000000")
你在找這個嗎?
list2 <- setNames(apply(list1, 1, \(x) as.list(x[-1])), list1[[1]])
list2$keeping
# $V2
# [1] "4.53"
#
# $V3
# [1] "4.95"
#
# $V4
# [1] "1"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.