简体   繁体   English

如何使用tidyr通过使用列名的字符串删除列来收集data.table?

[英]How to use tidyr to gather a data.table by removing columns using the column names' string?

Seems to have found a bug in tidyr. 似乎在提迪尔发现了一个小虫。

I have a piece of code like this 我有一段这样的代码

 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()

But

    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))  

works. 作品。

The only difference is that one set of code is in a function but the other is not! 唯一的区别是一组代码在一个函数中,而另一组则不在!

I'm just adding an answer here to show the function and standalone code have identical results once dt2 is added to the last line of the a() function (as suggested by @A5C1D2H2I1M1N2O1R2T1 in the comments). 我只是在这里添加一个答案,以显示该函数,并且将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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM