每次第 2、3 或 4 列中的行值发生变化时,转置第 5-8 列
Transpose columns 5-8, every time the row value changes in columns 2, 3 or 4
这是我的数据集
我想做的是每次有新管(或新菌落或新样品)时转置最后 4 列
因此转变为这样的东西:
我一直在尝试在 R 中执行此操作,但我愿意接受其他建议,非常感谢任何帮助!
ok 找到了解决方案(对于以后可能遇到类似问题的人)
在下面的示例数据中,我假设第 2 列和第 3 列必须保留,而第 4-6 列需要调换。
我使用了“unstack”,这使得任务变得非常简单,可能有更简单的方法来解决这个问题,但这对我来说效果很好,所以我就把它留在那里。
创建数据
x <- data.frame("SN" = 1:24, "Tube" = c(1,1,1,1,1,1,1,1,3,3,3,3,3,3,3,3,5,5,5,5,5,5,5,5),
"Name" = c("John","John","John","John","John","John","John","John","Dora","Dora","Dora","Dora","Dora","Dora","Dora","Dora","Nick","Nick","Nick","Nick","Nick","Nick","Nick","Nick"))
x$CP1 <- sample(40, size = nrow(x), replace = TRUE)
x$CP2 <- sample(40, size = nrow(x), replace = TRUE)
x$CP3 <- sample(40, size = nrow(x), replace = TRUE)
转化
tmp1 <- data.frame(CP1=x$CP1, ind=rep(1:8, nrow(x)/8))
tmp2 <- data.frame(CP2=x$CP2, ind=rep(1:8, nrow(x)/8))
tmp3 <- data.frame(CP3=x$CP3, ind=rep(1:8, nrow(x)/8))
new1=unstack(tmp1, CP1~ind)
new2=unstack(tmp2, CP2~ind)
new3=unstack(tmp3, CP3~ind)
z=unique(x[2:3])
tmp1=cbind(z,new1)
tmp2=cbind(z,new2)
tmp3=cbind(z,new3)
new.data=rbind(tmp1,tmp2,tmp3)
这是我的数据集
我想做的是每次有新管(或新菌落或新样品)时转置最后 4 列
因此转变为这样的东西:
我一直在尝试在 R 中执行此操作,但我愿意接受其他建议,非常感谢任何帮助!
ok 找到了解决方案(对于以后可能遇到类似问题的人)
在下面的示例数据中,我假设第 2 列和第 3 列必须保留,而第 4-6 列需要调换。
我使用了“unstack”,这使得任务变得非常简单,可能有更简单的方法来解决这个问题,但这对我来说效果很好,所以我就把它留在那里。
创建数据
x <- data.frame("SN" = 1:24, "Tube" = c(1,1,1,1,1,1,1,1,3,3,3,3,3,3,3,3,5,5,5,5,5,5,5,5),
"Name" = c("John","John","John","John","John","John","John","John","Dora","Dora","Dora","Dora","Dora","Dora","Dora","Dora","Nick","Nick","Nick","Nick","Nick","Nick","Nick","Nick"))
x$CP1 <- sample(40, size = nrow(x), replace = TRUE)
x$CP2 <- sample(40, size = nrow(x), replace = TRUE)
x$CP3 <- sample(40, size = nrow(x), replace = TRUE)
转化
tmp1 <- data.frame(CP1=x$CP1, ind=rep(1:8, nrow(x)/8))
tmp2 <- data.frame(CP2=x$CP2, ind=rep(1:8, nrow(x)/8))
tmp3 <- data.frame(CP3=x$CP3, ind=rep(1:8, nrow(x)/8))
new1=unstack(tmp1, CP1~ind)
new2=unstack(tmp2, CP2~ind)
new3=unstack(tmp3, CP3~ind)
z=unique(x[2:3])
tmp1=cbind(z,new1)
tmp2=cbind(z,new2)
tmp3=cbind(z,new3)
new.data=rbind(tmp1,tmp2,tmp3)