我是一个R(和编码新手),我正在寻找一种方法来重新配置表A显示到表B。
表A:
type x1 x2 x3
A 4 6 9
A 7 4 1
A 9 6 2
B 1 3 8
B 2 7 9我正在寻找将转换为以下代码的代码
表B:
type x1 x2 x3 x1' x2' x3' x1'' x2'' x3''
A 4 6 9 7 4 1 9 6 2
B 1 3 8 2 7 9 真正的表A是超过150000行和36列。具有2100唯一的“类型”值。
谢谢你的帮助。
-Shawn
发布于 2016-06-21 00:22:43
在我看来,这个解决方案很简单。
# split the data frame by type and use unlist, which will provide names
ld <- lapply(split(d[-1], d[["type"]]), unlist)
# gather all the unique names in the list
ldNames <- Reduce(unique, lapply(ld, names))
# use the names to index each list element, which makes them
# all of equal length and suitable for row binding.
do.call(rbind, lapply(ld, function(x) x[ldNames]))
# x11 x12 x13 x21 x22 x23 x31 x32 x33
# A 4 7 9 6 4 6 9 1 2
# B 1 2 NA 3 7 NA 8 9 NA如果上面的输出顺序不令人满意,您可以重新排列:
# save the output from above
d2 <- do.call(rbind, lapply(ld, function(x) x[ldNames]))
# reorder the names
ldNames_sorted <- c(matrix(ldNames, ncol = (ncol(d) - 1), byrow = TRUE))
# apply the new order.
d2 <- d2[, ldNames_sorted]
# x11 x21 x31 x12 x22 x32 x13 x23 x33
#A 4 6 9 7 4 1 9 6 2
#B 1 3 8 2 7 9 NA NA NA若要为类型添加列而不是使用行名,一种方法是:
data.frame(type = row.names(d2), d2)发布于 2016-06-21 06:45:55
聚会有点晚了,但是使用data.table包的data.table函数也可以很容易地做到这一点,因为可以在其中使用多个value.var:
library(data.table)
dcast(setDT(d), type ~ rowid(type), value.var = c('x1','x2','x3'), sep = '')这意味着:
type x11 x12 x13 x21 x22 x23 x31 x32 x33 1: A 4 7 9 6 4 6 9 1 2 2: B 1 2 NA 3 7 NA 8 9 NA
您也可以在基R中这样做:
d$num <- ave(d$x1, d$type, FUN = seq_along)
reshape(d, idvar = 'type', direction = 'wide', timevar = 'num', sep = '')发布于 2016-06-20 22:45:21
试试看,解决办法不那么简明扼要,只是给你一个提示,我认为很多东西都可以改进。
但最后,我们必须在这里引入NAs:
zz <- "type x1 x2 x3
A 4 6 9
A 7 4 1
A 9 6 2
B 1 3 8
B 2 7 9"
dA <- read.table(text=zz, header=T)
tmp<-(sapply(unique(dA$type), FUN=function(x) as.vector(t(dA[dA$type == x, -1]))))
t(sapply(tmp, '[', seq(max(sapply(tmp, length)))))
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
[1,] 4 6 9 7 4 1 9 6 2
[2,] 1 3 8 2 7 9 NA NA NAhttps://stackoverflow.com/questions/37932414
复制相似问题