Transpose whole dataframe into one row dataframe- (or transposing each row of data.table and column binding)

时间:2018-02-01 18:21:07

标签: r data.table reshape reshape2

I have tried to transform my_dataset with the help of library reshape & data.table in order to achieve the result.dataset but haven't been successful as yet.

I have a data table my_dataset that looks like this :-

A    X     Count
id1  b     1
id1  c     2

And I want to have the result.dataset that should look like this :-

 A   X1  Count1  X2  Count2  
 id1  b    1      c    2

It would be great if anyone could help me to get the result.dataset as above, preferably by using reshape or data.table (or both lib).

3 个答案:

答案 0 :(得分:2)

这是一个仅使用reshape2的解决方案(试图坚持使用建议的软件包)。首先添加一个rep列,允许用户调用dcast

require(reshape2)

#adding rep
my_dataset$rep = unlist(tapply(my_dataset$A, my_dataset$A, function(x)1:length(x)))

#cast at work
C1 = dcast(my_dataset, A ~ paste('X',rep, sep=''), value.var='X')
C2 = dcast(my_dataset, A ~ paste('Count',rep, sep=''), value.var='Count')

result.dataset = cbind(C1, C2[,-1])

但是,这些列与您的示例的顺序不同。

答案 1 :(得分:1)

我们可以聚合行并使用cSplit拆分它们。

library(data.table)
library(splitstackshape)

dat2 <- setDT(dat)[, lapply(.SD, paste, collapse = ","), by = A]

cols <- c(names(dat[, 1]), paste(names(dat[, -1]), 
                                 rep(1:nrow(dat), each = nrow(dat), 
                                 sep = "_"))

cSplit(dat2, splitCols = names(dat[, -1]))[, cols, with = FALSE]
#      A X_1 Count_1 X_2 Count_2
# 1: id1   b       1   c       2

数据

dat <- read.table(text = "A    X     Count
id1  b     1
id1  c     2",
                  header = TRUE, stringsAsFactors = FALSE)

答案 2 :(得分:1)

试试这个:

dt <- read.table(text = 'A    X     Count
id1  b     1
id1  c     2',header=T)
a <- aggregate(.~A, dt, paste, collapse=",")
library(splitstackshape)
result <- concat.split.multiple(data = a, split.cols = c("X","Count"), seps = ",")

输出:

> result
A X_1 X_2 Count_1 Count_2
1: id1   b   c       1       2