收集以数字开头的列

时间:2016-09-30 17:12:21

标签: r

我有这个数据框

 first = quantile(c(1,2,3),c(.5,.6)) 
  second = quantile(c(7,78,8),c(.5,.6)) 
  main =as.data.frame(rbind(first, second))
  main$group = cbind(  as.character(rownames(main) ) )
  main

       50%  60%  group
first    2  2.2  first
second   8 22.0 second

我希望用聚集转换它,但是我收到了错误:

  main %>% gather(key= Percentile, value = value, c("50%","60%"))
Error: All select() inputs must resolve to integer column positions.
The following do not:
*  c("50%", "60%")

结果应为:

group    Percentile    value
first     50%                2
first     60%                 2.2
second    50%                8
second    60%                  22

谢谢

2 个答案:

答案 0 :(得分:2)

这是:

main %>% gather(Percentile, value = value,c(`50%`, `60%`))
   group Percentile value
1  first        50%   2.0
2 second        50%   8.0
3  first        60%   2.2
4 second        60%  22.0

答案 1 :(得分:1)

我不知道gatherlibrary(reshape2)会做你想做的事

reshape2::melt(main, id.vars = "group")

   group variable value
1  first      50%   2.0
2 second      50%   8.0
3  first      60%   2.2
4 second      60%  22.0

您可以使用gather,而不是使用当前拥有的列名称。你真的不应该使用带有算术/特殊字符的名字。

colnames(main) <- c("fifty", "sixty", "group")
gather(main, key = group, value = number, fifty, sixty)

   group group number
1  first fifty    2.0
2 second fifty    8.0
3  first sixty    2.2
4 second sixty   22.0