2017-05-13 1 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 

は、私は、データフレームにすべてを抽出するために望んでいたが、理由は再帰的なインデックス・エラーのために、それはdoesnの仕事はありません。

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)からMapを使用することができます。 %df%>%select(one_of(variables_to_extract))%>%map(コメント) 'またはベースで' lapply(df [、variables_to_extract]、comment) ' – alistaire

答えて

3

data.frameがリストであるので、あなたはそれぞれのベクトルに機能(例えばcomment)を適用するlapplyまたはpurrr::mapを使用することができ、それが含まれています

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 

をAにそれを置くために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

我々はbase R

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

#$b 
#[1] "Some description" 

#$e 
#NULL 
関連する問題