如何使用tidyr :: spread值参数及其值存储为字符串变量?

时间:2017-11-03 14:13:40

标签: r tidyr

我在一个周期内运行了多个tidyr::spread,其中value参数的值发生了变化。但是,value要求"裸(未引用)名称" ...

mydata <- structure(list(ID = c(26242055, 26242254, 26243093, 26248278, 
26252563, 26255141, 26242055), Target = c(0, 0, 0, 0, 0, 0, 0
), opendt = c("2013-01-31", "2013-01-31", "2013-01-31", "2013-01-31", 
"2013-01-31", "2013-01-31", "2013-01-31"), txn_bc_am_cnt = c(1, 
2, 1, 27, 1, 2, 1), txn_bc_am_sum = c(200000, 19040.02, 35000, 
143227.5, 11910, 32212.8, 200000), delta = c(1, 1, 2, 2, 2, 3, 
3)), .Names = c("ID", "Target", "opendt", "txn_bc_am_cnt", "txn_bc_am_sum", 
"delta"), row.names = c(NA, 7L), class = "data.frame")

x <- c("txn_bc_am_sum", "txn_bc_am_cnt")

这样可行:

tidyr::spread(mydata[,c("ID", "Target", "opendt", x[1], "delta")], 
key = delta, value = txn_bc_am_sum)

但这失败了:

tidyr::spread(mydata[,c("ID", "Target", "opendt", x[1], "delta")], 
key = delta, value = x[1])

如何更改value?我确信有一个优雅的解决方法,但我无法弄清楚。

1 个答案:

答案 0 :(得分:4)

tidyr函数似乎不支持新的rlang语法,所以现在最好的选择是使用函数的?spread_标准评估版本

tidyr::spread_(mydata[,c("ID", "Target", "opendt", x[1], "delta")], 
    key_col = "delta", value_col = x[1])