我有一个如下所示的数据框:
inten new.probes
12.28280 AFFX-r2-P1-cre-5_at
12.35039 AFFX-r2-P1-cre-5_at
12.38397 AFFX-r2-P1-cre-5_at
12.36304 AFFX-r2-P1-cre-5_at
12.16271 AFFX-r2-P1-cre-5_at
12.70304 AFFX-r2-P1-cre-3_at
12.28280 AFFX-r2-P1-cre-3_at
12.35039 AFFX-r2-P1-cre-3_at
12.38397 AFFX-r2-P1-cre-3_at
12.36304 AFFX-r2-P1-cre-3_at
12.16271 AFFX-r2-P1-cre-2_at
12.70304 AFFX-r2-P1-cre-2_at
12.16271 AFFX-r2-P1-cre-2_at
12.70304 AFFX-r2-P1-cre-2_at
(上面的形式为两个单独的列,其中probenames为一列,信号强度值为other) 我希望以下列方式转换数据框:
AFFX-r2-P1-cre-5_at 12.28280 12.35039 12.38397 12.36304 12.16271
AFFX-r2-P1-cre-3_at 12.28280 12.35039 12.38397 12.36304 12.16271
AFFX-r2-P1-cre-2_at 12.38304 12.36304 12.38397 12.16271 12.70304
欢迎任何建议。这是一个很大的数据集,我只给了它一小部分求助。
答案 0 :(得分:3)
如果new.probes
的值具有相同数量的元素,则可以使用:
do.call(rbind, unstack(dat))
[,1] [,2] [,3] [,4] [,5]
AFFX-r2-P1-cre-2_at 12.16271 12.70304 12.16271 12.70304 12.16271
AFFX-r2-P1-cre-3_at 12.70304 12.28280 12.35039 12.38397 12.36304
AFFX-r2-P1-cre-5_at 12.28280 12.35039 12.38397 12.36304 12.16271
Warning message:
In function (..., deparse.level = 1) :
number of columns of result is not a multiple of vector length (arg 1)
但这显然是错误的 - 您需要使用NA
填充较短的向量:
x <- unstack(dat)
m <- max(sapply(x, length))
do.call(rbind, lapply(x, function(x)c(x, rep(NA, m-length(x)))))
[,1] [,2] [,3] [,4] [,5]
AFFX-r2-P1-cre-2_at 12.16271 12.70304 12.16271 12.70304 NA
AFFX-r2-P1-cre-3_at 12.70304 12.28280 12.35039 12.38397 12.36304
AFFX-r2-P1-cre-5_at 12.28280 12.35039 12.38397 12.36304 12.16271
答案 1 :(得分:1)
这就是我如何处理这个问题:
new.probes
变量已排序。sequence()
和rle()
为每个new.probes
生成“时间”变量。reshape()
转换数据。这是一个包含样本数据的工作示例(假设它名为“DF”)。
DF = DF[order(DF$new.probes), ]
DF$time = sequence(rle(as.vector(DF$new.probes))$lengths)
reshape(DF, direction = "wide", idvar = "new.probes", timevar = "time")
# new.probes inten.1 inten.2 inten.3 inten.4 inten.5
# 11 AFFX-r2-P1-cre-2_at 12.16271 12.70304 12.16271 12.70304 NA
# 6 AFFX-r2-P1-cre-3_at 12.70304 12.28280 12.35039 12.38397 12.36304
# 1 AFFX-r2-P1-cre-5_at 12.28280 12.35039 12.38397 12.36304 12.16271
或者,如果您希望reshape2
中的语法基于R reshape
,请将步骤3替换为:
require(reshape2)
dcast(DF, new.probes ~ time, value.var = "inten")