简体   繁体   English

从 csv 到 R 创建嵌套列表

[英]Create nested list from csv in R

I have a CSV file that I used to create a list 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

Instead of the above list, I want to create a nested list in which V2, V3, V4 values will be in a sublist of each V1 element.我想创建一个嵌套列表,而不是上面的列表,其中 V2、V3、V4 值将位于每个 V1 元素的子列表中。 Can some good soul help in this?一些善良的灵魂可以帮助吗?

It is usually not good practice to name an object by a function (here, list is also a function);用 function 来命名 object 通常不是好的做法(这里, list也是一个函数); you can use eg list1 .您可以使用例如list1

library(tidyverse)

list1 %>% 
  group_by(V1) %>% 
  summarise(across(V2:V4, list)) %>% 
  transpose()

If you want to keep the column order, you have to transformed variable to factor, and then since purrr::transpose coerces factors to numeric, you have to use pmap(list) .如果要保持列顺序,则必须将变量转换为因子,然后由于purrr::transpose将因子强制转换为数字,因此必须使用pmap(list)

list1 %>% 
  group_by(V1 = as_factor(V1)) %>% 
  summarise(across(V2:V4, list)) %>% 
  pmap(list)

output 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

data数据

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")

Are you looking for this?你在找这个吗?

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM