【问题标题】:Accessing (attributes of) a list of variables from a data frame based on a vector基于向量从数据框中访问变量列表(的属性)
【发布时间】: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 %&gt;% select(one_of(variables_to_extract)) %&gt;% map(comment) 或在基地,lapply(df[, variables_to_extract], comment)

标签: r dplyr attr


【解决方案1】:

由于 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 进行简化。

【讨论】:

    【解决方案2】:

    我们可以使用base R中的Map

    Map(comment, df[variables_to_extract])
    #$a
    #[1] "Some explanation"
    
    #$b
    #[1] "Some description"
    
    #$e
    #NULL
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-06
      • 1970-01-01
      • 1970-01-01
      • 2012-05-08
      • 2020-07-13
      • 2018-01-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多