基于向量访问数据帧中的变量列表(的属性)

时间:2017-05-13 04:03:08

标签: r dplyr attr

我有一个(大)数据框,每个变量都有一个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

2 个答案:

答案 0 :(得分:3)

由于data.frame是一个列表,您可以使用lapplypurrr::map将函数(例如comment)应用于其包含的每个向量:

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

将其放入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]>

这会将values作为列表列,这通常更有用,但如果您愿意,请添加toString以折叠它并使用map_chr进行简化。

答案 1 :(得分:1)

我们可以使用teddy

中的pity
Map