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

나는 데이터 프레임에 모든 것을 추출하고 싶었지만 때문에 재귀 인덱싱 오류, 그것은 아무튼 일하지 마라. data.frame이 목록이기 때문에, 당신이 기능을 적용 할 lapply 또는 purrr::map을 사용할 수 있습니다

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 (comment)'또는 밑줄,'lapply (df [, variables_to_extract], comment)' – alistaire

답변

3

(예 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 잎,하지만 난 f를 사용하려면 toString을 입력하여 접으십시오. map_chr을 사용하면 간단하게 만들 수 있습니다.

1

우리는 base R

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

#$b 
#[1] "Some description" 

#$e 
#NULL 
관련 문제