2017-11-30 13 views
2

のdplyr :: recodeの名前付き置換えに拡張する私は、同じデータ変換をしばしばやっているだけで、名前と列数の違いがあります。例えば、私の実際のデータで...を使用して関数を書く...そして、R

library(tidyverse) 

test.data <- tribble(
    ~id.num, ~site, ~value1, ~value2, ~value3, 
    "10-01", "log", 1.5, 2.5, 3.5, 
    "10-02", "branch", 0.7, 2, 3.24, 
    "10-03", "branch", 3.2, 2.3, 7.7 
) 

test.data <- 
    gather(
    test.data, 
    key = "test.code", 
    value = "values", 
    "value1", 
    "value2", 
    "value3" 
) %>% 
    mutate(
    test.code.order = recode(
     test.code, 
     "value1" = 1, 
     "value2" = 2, 
     "value3" = 3 
    ) 
) %>% 
    arrange(id.num, test.code.order) 

は、一般的に代わり3の収集されて16-30の列があります現在、私はのmutateの名前が付いたペアを作成するためにやって終わる何

c(
    "value1", 
    "value2", 
    "value3" 
) -> columns 

cat(paste0('"', columns, '" = ', 1:length(columns)), sep = ",\n") 

とコピーとあります出力をコードに貼り付けます。

しかし、私は何をできるようにしたいことは

test.data <- wide.to.long(test.data, "value1", "value2", "value3") 

は私に上記gathermutatearrangeパイプと同じ結果を与えるような関数を作成しています。私は

wide.to.long <- function(df, key = "test.code", value = "values", id = "id.num", ...) { 
    test.order.numbers <- missing.code.here 
    gather(df, key, value, ...) %>% 
    mutate(test.code.order = recode(key, test.order.numbers)) %>% 
    arrange(id, test.code.order) 
} 

もちろんcat

が動作しない、など "value1" = 1私はそれがこのような何かを見てね想像

"value1"から拡大した文字列を取得するに取り掛かるするかどうかはわかりませんし、任意のpasteのバージョン私はエラーを与える試しました:"Argument 2 must be named, not unnamed"。私は何が欠けていますか?

答えて

1
wide.to.long <- function(df, ..., key = "test.code", 
         value = "values", id = "id.num") { 
    v <- quos(...) 
    key <- rlang::sym(key) 
    key <- enquo(key) 
    id <- rlang::sym(id) 
    id <- enquo(id) 
    test.order.numbers <- setNames(seq_along(v), sapply(v, quo_name)) 
    gather(df, !! key, !! value, !!! v) %>% 
    mutate(test.code.order = recode(!! key, !!! test.order.numbers)) %>% 
    arrange(!! id, test.code.order) 
} 

wide.to.long(test.data, "value1", "value2", "value3") 

# # A tibble: 9 x 5 
# id.num site test.code values test.code.order 
# <chr> <chr>  <chr> <dbl>   <int> 
# 1 10-01 log value1 1.50    1 
# 2 10-01 log value2 2.50    2 
# 3 10-01 log value3 3.50    3 
# 4 10-02 branch value1 0.70    1 
# 5 10-02 branch value2 2.00    2 
# 6 10-02 branch value3 3.24    3 
# 7 10-03 branch value1 3.20    1 
# 8 10-03 branch value2 2.30    2 
# 9 10-03 branch value3 7.70    3 

または、直接変数名をwide.to.long(test.data, value1, value2, value3)に渡すことができます。

+0

'' id.num'の代わりに '' id''を使用してください。 –

+0

@CTHall最後に修正されました –

関連する問題