A simple question: How to extract multiple data from lists with multiple entries.
> data
[[1]]
a b p d e f g h i j k l m n
0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 1.1 1.2 1.3 1.4
[[2]]
a b p d e f g h i j k l m n
0.4 0.2 0.5 0.4 0.8 1.6 0.5 0.8 0.1 1.9 1.3 2.2 1.3 1.4
[[3]]
a b p d e f g h i j k l m n
0.6 0.8 2.3 3.4 1.5 2.6 1.7 1.8 0.8 1.5 1.0 1.0 1.4 1.6
[[4]]
a b p d e f g h i j k l m n
0.5 0.1 0.8 1.4 1.5 1.6 2.7 0.8 0.9 1.9 1.2 1.3 1.5 1.0
There are actually 1000 lists (only shown 4 for simplicity). The a, b, p, ..., n are actually names that I have given in another function which returns
return(c("a" = a, "b" = b, ..., "n" = n))
How do I extract so that I will get the following results
#For a values
> data$a
0.1 0.4 0.6 0.5
#For b values
> data$b
0.2 0.2 0.8 0.1
I am also open to changing the list to matrices or vectors and then extracting them. Any method that works are welcome. Thank you.
CodePudding user response:
First provide the data in reproducible format using dput(data)
:
dput(data)
list(structure(list(a = 0.1, b = 0.2, p = 0.3, d = 0.4, e = 0.5,
f = 0.6, g = 0.7, h = 0.8, i = 0.9, j = 1, k = 1.1, l = 1.2,
m = 1.3, n = 1.4), row.names = 1L, class = "data.frame"),
structure(list(a = 0.4, b = 0.2, p = 0.5, d = 0.4, e = 0.8,
f = 1.6, g = 0.5, h = 0.8, i = 0.1, j = 1.9, k = 1.3,
l = 2.2, m = 1.3, n = 1.4), row.names = 2L, class = "data.frame"),
structure(list(a = 0.6, b = 0.8, p = 2.3, d = 3.4, e = 1.5,
f = 2.6, g = 1.7, h = 1.8, i = 0.8, j = 1.5, k = 1, l = 1,
m = 1.4, n = 1.6), row.names = 3L, class = "data.frame"),
structure(list(a = 0.5, b = 0.1, p = 0.8, d = 1.4, e = 1.5,
f = 1.6, g = 2.7, h = 0.8, i = 0.9, j = 1.9, k = 1.2,
l = 1.3, m = 1.5, n = 1), row.names = 4L, class = "data.frame"))
Since the data consist of rows of data with the same columns, the simplest approach would be to convert to a matrix:
data.mat <- do.call(rbind, data)
# a b p d e f g h i j k l m n
# 1 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 1.1 1.2 1.3 1.4
# 2 0.4 0.2 0.5 0.4 0.8 1.6 0.5 0.8 0.1 1.9 1.3 2.2 1.3 1.4
# 3 0.6 0.8 2.3 3.4 1.5 2.6 1.7 1.8 0.8 1.5 1.0 1.0 1.4 1.6
# 4 0.5 0.1 0.8 1.4 1.5 1.6 2.7 0.8 0.9 1.9 1.2 1.3 1.5 1.0
data.mat$a
# [1] 0.1 0.4 0.6 0.5
You can also work directly with the list:
sapply(data, "[[", "a")
# 0.1 0.4 0.6 0.5
CodePudding user response:
How about this, first using (base) lapply and then map from the purrr package:
data <- list(
x = c(a = 0.1, b = 0.2),
y = c(a = 0.4, b = 0.2)
)
lapply(data, '[[', 1)
lapply(data, '[[', "a")
library(purrr)
map(data, `[[`, 1)