使用同一键将数据合并到一行 [英] Merge data with same key to one row

查看:68
本文介绍了使用同一键将数据合并到一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框,上面有几个数据

I have a data frame with several data like this

Key     A B C
1       1 2 3
1       4 6 8
1       3 2 1

我需要像这样将这些具有相同键的数据合并到一行中

i need to merge these data with same key into one row just like this

Key      A1 B1 C1 A2 B2 C2 A3 B3 C3
1        1  2  3  4  6  8  3  2  1 

有什么简单的方法可以得到我需要的结果.

is there any easy way to get this result what i need.

推荐答案

如果这只是一组键",则一种选择是使用base R.我们将第一列(df[-1])以外的数据集转置(t),连接到vector,并使用第一列的第一元素转换为data.frmecbind.

If this is only a single group of 'key', one option would be to use base R. We transpose (t) the dataset except the first column (df[-1]), concatenate to a vector, convert to data.frme and cbind with the first element of the first column.

res <- cbind(df1[1,1], as.data.frame.list(c(t(df1[-1]))))
names(res) <- c(names(df1)[1] ,make.unique(rep(names(df1)[-1],3)))
res
#  Key A B C A.1 B.1 C.1 A.2 B.2 C.2
#1   1 1 2 3   4   6   8   3   2   1


或者如果有许多关键"元素,请使用data.table,即开发版本v1.9.7


Or use data.table i.e. the development version v1.9.7 if there are many 'Key' elements

library(data.table)
dcast(setDT(df1), Key~rowid(Key), value.var = c("A", "B", "C"),sep="")
#   Key A1 A2 A3 B1 B2 B3 C1 C2 C3
#1:   1  1  4  3  2  6  2  3  8  1

(如果我们有版本为<的data.table). v1.9.7,我们需要创建按键"分组的序列列.

if we have a data.table with version < v1.9.7, we need to create the sequence column grouped by 'Key'.

dcast(setDT(df1)[, rn := 1:.N , Key], Key ~rn, value.var = c("A", "B", "C"),sep="")
#   Key A1 A2 A3 B1 B2 B3 C1 C2 C3
#1:   1  1  4  3  2  6  2  3  8  1

这篇关于使用同一键将数据合并到一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆