I have a CSV file that I used to create a list in 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. Can some good soul help in this?
CodePudding user response:
It is usually not good practice to name an object by a function (here, list
is also a function); you can use e.g. 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)
.
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
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")
CodePudding user response:
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"