Accessing (attributes of) a list of variables from a data frame based on a vector

Viewed 2458

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
2 Answers
Related