合并具有相同 ID 变量的行 [英] Merging rows with the same ID variable

查看:39
本文介绍了合并具有相同 ID 变量的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 R 中有一个数据框,其中包含 2186 个 obs 和 38 个变量.行有一个 ID 变量,指的是独特的实验并使用

I have a dataframe in R with 2186 obs of 38 vars. Rows have an ID variable referring to unique experiments and using

length(unique(df$ID))==nrow(df)

n_occur<-data.frame(table(df$ID))

我知道我的 327 行有重复的 ID,其中一些 ID 重复多次.我正在尝试合并具有相同 ID 的行,因为这些行不是重复的,而是给定实验中的第二、第三等观察结果.

I know 327 of my rows have repeated IDs with some IDs repeated more than once. I am trying to merge rows with the same ID as these aren't duplicates but just second, third etc. observations within a given experiment.

例如,如果我有

x y ID
1 2 a
1 3 b
2 4 c
1 3 d
1 4 a
3 2 b
2 3 a

我想结束

x y ID x2 y2 ID2 x3 y3 ID3
1 2 a  1  4  a   2  3  a
1 3 b  3  2  b  na na na
2 4 c  na na na na na na
1 3 d  na na na na na na

我看到过类似的 SQL 和 php 问题,但这对我在 R 中的尝试没有帮助.任何帮助将不胜感激.

I've seen similar questions for SQL and php but this hasn't helped me with my attempts in R. Any help would be gratefully appreciated.

推荐答案

您可以使用 包,您可以在其中选择多个值变量.使用 setDT(mydf) 您可以将数据帧转换为数据表,使用 [, idx := 1:.N, by = ID] 您可以通过 添加索引您随后在 dcast 公式中使用的 ID:

You could use the enhanced dcast function from the data.table package for that where you can select multiple value variables. With setDT(mydf) you convert your dataframe to a datatable and with [, idx := 1:.N, by = ID] you add a index by ID which you use subsequently in the dcast formula:

library(data.table)
dcast(setDT(mydf)[, idx := 1:.N, by = ID], ID ~ idx, value.var = c("x","y"))

或者使用开发版data.table (v1.9.7+),你可以使用新的rowid函数:

dcast(setDT(mydf), ID ~ rowid(ID), value.var = c("x","y"))

给出:

   ID x_1 x_2 x_3 y_1 y_2 y_3
1:  a   1   1   2   2   4   3
2:  b   1   3  NA   3   2  NA
3:  c   2  NA  NA   4  NA  NA
4:  d   1  NA  NA   3  NA  NA

<小时>

使用的数据:


Used data:

mydf <- structure(list(x = c(1L, 1L, 2L, 1L, 1L, 3L, 2L), y = c(2L, 3L, 
4L, 3L, 4L, 2L, 3L), ID = structure(c(1L, 2L, 3L, 4L, 1L, 2L, 
1L), .Label = c("a", "b", "c", "d"), class = "factor")), .Names = c("x", 
"y", "ID"), class = "data.frame", row.names = c(NA, -7L))

这篇关于合并具有相同 ID 变量的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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