r - how to manipulated data set into new data frame?
问题描述
my data look like this : 1-pre 2-mid 3-post
id<-c(1,2,3,4,5,6,7,8,9)
type<-c(1,2,2,1,2,1,1,1,2) #is the factor level 1 and 2
k1<-c(30.7,20.3,3.4,22,11.6,29.5,15.4,2.7,2.1)
k2<-c(13.4,11,1.4,9.6,17.3,27.1,9.3,5.3,4.7)
k3<-c(1.2,10,4.7,2.6,13.4,14.8,8.8,0.7,4.6)
m1<-c(12 ,12.6, 1.6, 6.2, 10.5, 8.6, 15.3, 1.5, 1.3)
m2<-c(6.6 ,10.5, 0.5, 2.7, 5.2, 8.5, 9.6, 0.6, 4.3)
m3<-c(2,11, 2.6,0.4,7.2,9.4,12.3,0.3,2)
df<-data.frame(type,k1,k2,k3,m1,m2,m3,id)
df[,1]<-as.factor(df[,1])
my new data frame look like this
type id time score
1 1 1 k1 30.7
2 1 1 k2 13.4
3 1 1 k3 1.2
4 1 1 m1 12.0
5 1 1 m2 6.6
6 1 1 m3 2.0
7 2 2 k1 20.3
8 2 2 k2 11.0
this command i use
dflong<-tidyr::gather(df,key=time, value=score, k1:k3,m1:m3)%>% arrange(id)
i want one column for period (pre,mid,post) and other column for value of m and k variable
解决方案
In base R, you could use reshape
function,. by specifying the varying columns ie 2:7
and then the separator for the varying columns to be ""
. if the columns had been named as k.1, k.2...
then the separator would have been .
reshape(df,2:7,dir="long",sep="")
type id time k m
1.1 1 1 1 30.7 12.0
2.1 2 2 1 20.3 12.6
3.1 2 3 1 3.4 1.6
4.1 1 4 1 22.0 6.2
5.1 2 5 1 11.6 10.5
6.1 1 6 1 29.5 8.6
7.1 1 7 1 15.4 15.3
8.1 1 8 1 2.7 1.5
9.1 2 9 1 2.1 1.3
1.2 1 1 2 13.4 6.6
2.2 2 2 2 11.0 10.5
3.2 2 3 2 1.4 0.5
4.2 1 4 2 9.6 2.7
5.2 2 5 2 17.3 5.2
6.2 1 6 2 27.1 8.5
7.2 1 7 2 9.3 9.6
8.2 1 8 2 5.3 0.6
9.2 2 9 2 4.7 4.3
1.3 1 1 3 1.2 2.0
2.3 2 2 3 10.0 11.0
3.3 2 3 3 4.7 2.6
4.3 1 4 3 2.6 0.4
5.3 2 5 3 13.4 7.2
6.3 1 6 3 14.8 9.4
7.3 1 7 3 8.8 12.3
8.3 1 8 3 0.7 0.3
9.3 2 9 3 4.6 2.0
推荐阅读
- android - 使用两个AppBaLayout,滚动RecyclerView的时候
- ansible - 如何使用ansible将日志文件从多主机复制到主机目录,由源主机ip命名的文件?
- javascript - Javascript 正则表达式在一行上匹配 XML 结束标记
- docker - 为什么要使用 docker 服务?
- spring - Drools7:如何将 drl 文件分配给 kmodule.xml 中的 KieBase?
- python - 对类中 -init_ 和 self 的使用感到困惑
- java - 使用反射启动 JavaFX 项目
- javascript - 如何更改任何图表水平仪表中的标记标签?
- react-native - 每次我进入页面时,React-native 都会渲染我的对象
- php - 服务弃用:Symfony 要求更改服务名称