Accessing (attributes of) a list of variables from a data frame based on a vector
attr, dplyr, r
Solution
Since a data.frame is a list, you can use `lapply` or `purrr::map` to apply a function (e.g. `comment`) to each vector it contains:
library(tidyverse)
df %>% select(one_of(variables_to_extract)) %>% map(comment) # in base R, lapply(df[variables_to_extract], comment)
#> $a
#> [1] "Some explanation"
#>
#> $b
#> [1] "Some description"
#>
#> $e
#> NULL
To put it in a data.frame,
data_frame(variable = variables_to_extract,
# iterate over variable, subset df and if NULL replace with NA; collapse to chr
description = map_chr(variable, ~comment(df[[.x]]) %||% NA),
values = map(variable, ~df[[.x]] %>% unique() %>% sort()))
#> # A tibble: 3 x 3
#> variable description values
#> <chr> <chr> <list>
#> 1 a Some explanation <int [5]>
#> 2 b Some description <int [5]>
#> 3 e <NA> <int [5]>
This leaves `values` as a list column, which is usually more useful, but if you'd rather, add in `toString` to collapse it and use `map_chr` to simplify.
Problem
I have a (big) data frame with variables which each have a `comment` attribute. ``` # Basic sample data df <- data.frame(a = 1:5, b = 5:1, c = 5:9, d = 9:5, e = 1:5) comment(df$a) <- "Some explanation" comment(df$b) <- "Some description" comment(df$c) <- "etc." ``` I would like to extract the `comment` attributes for some of those variables, as well as a lit of possible values. So I start by defining the list of variables I want to extract: ``` variables_to_extract = c("a", "b", "e") ``` I would normally work on a subset of the data frame, but then I cannot access the attributes (e.g., `comment`) nor the list of possible values of each variable. ``` library(tidyverse) df %>% select(one_of(variables_to_export)) %>% comment() # accesses only the 'comment' attribute of the whole data frame (df), hence NULL ``` I also tried to access through `df[[variables_to_export]]`, but it generates an error... ``` df[[variables_to_export]] # Error: Recursive Indexing failed at level 2 ``` I wanted to extract everything into a data frame, but because of the recursive indexing error, it doesn't work. ``` meta <- data.frame(variable = variables_to_export, description = comment(papers[[variables_to_export]]), values = papers[[vairables_to_export]] %>% unique() %>% na.omit() %>% sort() %>% paste(collapse = ", ")) # Error: Recursive Indexing failed at level 2 ```