如何通过使用列名称删除列来使用tidyr来收集data.table。串?

时间:2014-08-27 23:51:43

标签: r data.table dplyr tidyr

似乎在tidyr中发现了一个错误。

我有一段像这样的代码

 rm(hello)
 a <- function() {  
  dt <- data.table(`*stat*` = c("mean","max"), time = c(11, 12), val1 = c(1,2), val2 =c(3,4))
  hello <- "^(time)$"
  dt2 <- dt %>% gather(dimension, value, -matches("\\*stat\\*"), -matches(hello))  
}

a()

但是

    dt <- data.table(`*stat*` = c("mean","max"), time = c(11, 12), val1 = c(1,2), val2 =c(3,4))
hello <- "^(time)$"
dt2 <- dt %>% gather(dimension, value, -matches("\\*stat\\*"), -matches(hello))  

作品。

唯一的区别是一组代码在一个函数中,而另一组不在!

1 个答案:

答案 0 :(得分:0)

我只是在这里添加一个答案,以显示函数和独立代码在dt2函数的最后一行添加a()后具有相同的结果(如@ A5C1D2H2I1M1N2O1R2T1所示)评论)。

library(tidyverse)

a <- function() {  
  dt <- data.table::data.table(`*stat*` = c("mean","max"), time = c(11, 12), val1 = c(1,2), val2 =c(3,4))
  hello <- "^(time)$"
  dt2 <- dt %>% gather(dimension, value, -matches("\\*stat\\*"), -matches(hello)) 
  dt2
}

a()
#>   *stat* time dimension value
#> 1   mean   11      val1     1
#> 2    max   12      val1     2
#> 3   mean   11      val2     3
#> 4    max   12      val2     4

dt <- data.table::data.table(`*stat*` = c("mean","max"), time = c(11, 12), val1 = c(1,2), val2 =c(3,4))
hello <- "^(time)$"
dt2 <- dt %>% gather(dimension, value, -matches("\\*stat\\*"), -matches(hello))  
dt2
#>   *stat* time dimension value
#> 1   mean   11      val1     1
#> 2    max   12      val1     2
#> 3   mean   11      val2     3
#> 4    max   12      val2     4

identical(a(), dt2)
#> [1] TRUE