Sebastian Zeki Sebastian Zeki - 11 days ago 5
R Question

how to gather columns which are numbered sequentially with tidyr

I have a set of columns as follows

rowid TimePoint2 TimePoint3 TimePoint4 TimePoint5 TimePoint6


I want to tidy the data but the gather function doesn't recognise the column names when I use he paste function
What I want is

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


etc

My code:

so instead of writing:

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


I want to write something like:

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


The error I get with the above is
Error: All select() inputs must resp;ve to integer column positions. The following do not: * paste (y,1:10,",",sep="")

Answer

I believe you can do:

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