2017-08-04 8 views
1

私の質問はどうすればいいですか? 例えば:私達への方法if..else ... dplyrチェインのr記入

select.vars <- function(data, price=TRUE){ 
    diamonds %>% {if (price) select(price) else select(carat)} 
} 
select.vars(diamonds) 

私はエラーを得た:

Error in UseMethod("select_") : 
    no applicable method for 'select_' applied to an object of class "logical" 

これは無意味な機能です。ちょうど説明の目的のために... ありがとう。

答えて

1

私たちは、私はちょうどそれを考え出したselect

select.vars <- function(data, price=TRUE){ 
    diamonds %>% 
       select(if(price) "price" else "carat") 
} 

resprice <- select.vars(diamonds) 
rescarat <- select.vars(diamonds, FALSE) 
head(rescarat) 
# A tibble: 6 x 1 
# carat 
# <dbl> 
#1 0.23 
#2 0.21 
#3 0.23 
#4 0.29 
#5 0.31 
#6 0.24 

head(resprice) 
# A tibble: 6 x 1 
# price 
# <int> 
#1 326 
#2 326 
#3 327 
#4 334 
#5 335 
#6 336 
0

if/elseを使用することができます。各選択の.forを単に追加します。

select.vars <- function(data, price=TRUE){ 
    diamonds %>% {if (price) select(., price) else select(., carat)} 
} 
関連する問題