正在使用编写函数。。。并扩展到dplyr::R中的命名替换
我发现自己经常做相同的数据转换,唯一的区别是列的名称和数量。比如说,正在使用编写函数。。。并扩展到dplyr::R中的命名替换,r,dplyr,tidyverse,R,Dplyr,Tidyverse,我发现自己经常做相同的数据转换,唯一的区别是列的名称和数量。比如说, 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 <- g
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)
以及将输出复制并粘贴到代码中
但是,我希望能够创建这样一个函数
test.data <- wide.to.long(test.data, "value1", "value2", "value3")
但是当然,
cat
不起作用,我尝试过的任何版本的paste
都会给我带来错误:“参数2必须命名,而不是未命名”
。我遗漏了什么?wide.to.long应该安排
使用id
而不是id.num
。
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 <- 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)
}
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