【发布时间】:2017-10-12 10:37:35
【问题描述】:
我有一个(大)数据框,其中包含变量,每个变量都有一个 comment 属性。
# 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."
我想为这些变量中的一些提取comment属性,以及一些可能的值。
所以我首先定义要提取的变量列表:
variables_to_extract = c("a", "b", "e")
我通常会处理数据框的一个子集,但是我无法访问属性(例如,comment),也无法访问每个变量的可能值列表。
library(tidyverse)
df %>% select(one_of(variables_to_export)) %>% comment()
# accesses only the 'comment' attribute of the whole data frame (df), hence NULL
我也尝试通过df[[variables_to_export]]访问,但是会报错...
df[[variables_to_export]]
# Error: Recursive Indexing failed at level 2
我想将所有内容提取到数据框中,但由于递归索引错误,它不起作用。
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
【问题讨论】:
-
library(tidyverse); df %>% select(one_of(variables_to_extract)) %>% map(comment)或在基地,lapply(df[, variables_to_extract], comment)