Reputation: 170
I have a pretty long nested list in R. My goal is to get an overview of the structure, i.e. variable names and optionally variable types (like int, chr etc.). I want to save this structure in a spreadsheet to show it to non-data people so that they understand which data we have available.
here is an example of a simplified nested list.
my_list <- list(
a = c(1,2,3),
b = list(
c = data.frame(
d = c(1,2),
e = c("a", "b")
)
),
f = list(
g = rep(1,10),
h = "a"
)
)
str(my_list)
List of 3
$ a: num [1:3] 1 2 3
$ b:List of 1
..$ c:'data.frame': 2 obs. of 2 variables:
.. ..$ d: num [1:2] 1 2
.. ..$ e: Factor w/ 2 levels "a","b": 1 2
$ f:List of 2
..$ g: num [1:10] 1 1 1 1 1 1 1 1 1 1
..$ h: chr "a"
so my goal is to have a tidy overview of the structure within my list. Similar to a database structure. I tried to save the str output in a variable via structure <- capture.output(str(my_list))
but this did not help me.
One example of an output can be:
names values
1 a num
2 d num
3 e chr
4 g num
5 h chr
Upvotes: 1
Views: 350
Reputation: 33498
Here is an idea:
struct <- rapply(my_list, class)
struct <- data.frame(
address = gsub(".", ">", names(struct), fixed = TRUE),
type = unname(struct)
)
struct
# address type
# 1 a numeric
# 2 b>c>d numeric
# 3 b>c>e factor
# 4 f>g numeric
# 5 f>h character
Upvotes: 2