2017-05-13 28 views
1

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

'库(tidyverse); df%>%select(one_of(variables_to_extract))%>%map(comment)'或者在base中,'lapply(df [,variables_to_extract],comment)'' – alistaire

回答

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

我们可以使用Mapbase R

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

#$b 
#[1] "Some description" 

#$e 
#NULL