如何将两行合并为一行,如
...
type1,-2.427,-32.962,-61.097
type2,0.004276057,0.0015271631,-0.005192355
type1,-2.427,-32.962,-60.783
type2,0.0018325958,0.0033597588,-0.0021380284
...
到
type1,-2.427,-32.962,-61.097,type2,0.004276057,0.0015271631,-0.005192355
type1,-2.427,-32.962,-60.783,type2,0.0018325958,0.0033597588,-0.0021380284
或
-2.427,-32.962,-61.097,0.004276057,0.0015271631,-0.005192355
-2.427,-32.962,-60.783,0.0018325958,0.0033597588,-0.0021380284
在GNU R?
答案 0 :(得分:3)
他们总是交替1/2吗?如果是这样,您可以使用基本索引。使用此示例data.frame
dd<-structure(list(V1 = structure(c(1L, 2L, 1L, 2L), .Label = c("type1",
"type2"), class = "factor"), V2 = c(-2.427, 0.004276057, -2.427,
0.0018325958), V3 = c(-32.962, 0.0015271631, -32.962, 0.0033597588
), V4 = c(-61.097, -0.005192355, -60.783, -0.0021380284)), .Names = c("V1",
"V2", "V3", "V4"), row.names = c(NA, 4L), class = "data.frame")
你可以做到
cbind(dd[seq(1,nrow(dd), by=2),], dd[seq(2,nrow(dd), by=2),])
# V1 V2 V3 V4 V1 V2 V3 V4
# 1 type1 -2.427 -32.962 -61.097 type2 0.004276057 0.001527163 -0.005192355
# 3 type1 -2.427 -32.962 -60.783 type2 0.001832596 0.003359759 -0.002138028
包含“type”列,或者你可以
cbind(dd[seq(1,nrow(dd), by=2),-1], dd[seq(2,nrow(dd), by=2),-1])
# V2 V3 V4 V2 V3 V4
# 1 -2.427 -32.962 -61.097 0.004276057 0.001527163 -0.005192355
# 3 -2.427 -32.962 -60.783 0.001832596 0.003359759 -0.002138028
将其关闭
答案 1 :(得分:2)
这是使用@ MrFlick的样本数据的另一种选择:
## Use `ave` to create an indicator variable
dd$ind <- with(dd, ave(as.numeric(V1), V1, FUN = seq_along))
## use `reshape` to "merge" your rows by indicator
reshape(dd, direction = "wide", idvar = "ind", timevar = "V1")
# ind V2.type1 V3.type1 V4.type1 V2.type2 V3.type2 V4.type2
# 1 1 -2.427 -32.962 -61.097 0.004276057 0.001527163 -0.005192355
# 3 2 -2.427 -32.962 -60.783 0.001832596 0.003359759 -0.002138028
答案 2 :(得分:1)
您可以使用split
按类型拆分数据,然后使用cbind
将它们组合在一起。以下方法从结果中删除第一列([-1]
),并使用MrFlick的数据dd
,
> do.call(cbind, split(dd[-1], dd[[1]]))
# type1.V2 type1.V3 type1.V4 type2.V2 type2.V3 type2.V4
# 1 -2.427 -32.962 -61.097 0.004276057 0.001527163 -0.005192355
# 3 -2.427 -32.962 -60.783 0.001832596 0.003359759 -0.002138028
在我的机器上,我认为这是当前三个答案中最快的。