【问题标题】:how to gather columns which are numbered sequentially with tidyr如何收集用tidyr按顺序编号的列
【发布时间】:2016-11-28 19:30:35
【问题描述】:

我有一组列如下

rowid   TimePoint2   TimePoint3    TimePoint4     TimePoint5    TimePoint6

我想整理数据,但是当我使用他的粘贴功能时,收集功能无法识别列名 我想要的是

rowid
1   TimePoint2    43
2   TimePoint3    34
3   TimePoint4    24
4   TimePoint5    22
5   TimePoint6    44

我的代码:

所以不要写:

y="TimePoint"
  Mydf<-
    select(df,matches(y),rowid)%>%
    gather(variable, value, TimePoint1,TimePoint2,TimePoint3,TimePoint4,TimePoint5,TimePoint6)

我想写这样的东西:

y="TimePoint"
  Mydf<-
    select(df,matches(y),rowid)%>%
    gather(variable, value, paste(y,1:10,",",sep=""))

我得到的错误是Error: All select() inputs must resp;ve to integer column positions. The following do not: * paste (y,1:10,",",sep="")

【问题讨论】:

  • 我认为您可以使用 dplyr 中的 starts_with,就像在 select() 中一样。
  • 好的,很好。请添加为答案

标签: r tidyr


【解决方案1】:

我相信你可以做到:

Mydf <- select(df,matches(y),rowid)%>%
    gather(variable, value, starts_with("TimePoint"))

【讨论】:

    【解决方案2】:

    由于您正在选择与“时间点”匹配的列,这也将起作用:

    library(dplyr)
    library(tidyr)
    y <- "TimePoint"
    Mydf <- df %>% select(rowid,matches(y)) %>% 
                   gather(variable,value,-1)
    print(Mydf)
    ##  rowid   variable value
    ##1     1 TimePoint2    43
    ##2     1 TimePoint3    34
    ##3     1 TimePoint4    24
    ##4     1 TimePoint5    22
    ##5     1 TimePoint6    44
    

    在这里,我们像您一样 select,但将 rowid 列放在首位。然后使用-1 收集除第一列之外的所有列。

    数据:

    df <- structure(list(rowid = 1L, TimePoint2 = 43L, TimePoint3 = 34L, 
        TimePoint4 = 24L, TimePoint5 = 22L, TimePoint6 = 44L), .Names = c("rowid", 
    "TimePoint2", "TimePoint3", "TimePoint4", "TimePoint5", "TimePoint6"
    ), class = "data.frame", row.names = c(NA, -1L))
    ##  rowid TimePoint2 TimePoint3 TimePoint4 TimePoint5 TimePoint6
    ##1     1         43         34         24         22         44
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-28
      • 2016-08-14
      • 2018-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-09
      相关资源
      最近更新 更多