简体   繁体   English

从R中的列聚合函数提取数据

[英]Extract data from column aggregate function in R

I have a large database from which I have extracted a data value (x) using the aggregate function: 我有一个大型数据库,使用聚合函数从中提取了数据值(x):

library(plotrix)
aggregate(mydataNC[,c(52)],by=list(patientNC, siteNC, supNC),max)

OUTPUT: OUTPUT:

在此处输入图片说明

Each (x) value has a corresponding distance value in located in a column titled (dist) in this database. 每个(x)值在此数据库中标题为(dist)的列中都有一个对应的距离值。 What is the easiest way to extract the value dist and added to the table? 提取值dist并将其添加到表中的最简单方法是什么?

I'd probably start with merge() first. 我可能先从merge()开始。 Here's a small reproducible example you can use to see what's going on and modify it to use your data: 这是一个可复制的小示例,您可以用来查看发生了什么并对其进行修改以使用您的数据:

# generate bogus data and view it
x1 <- rep(c("A", "B", "C"), each = 4)
x2 <- rep(c("E", "E", "F", "F"), times = 3)
y1 <- rnorm(12)
y2 <- rnorm(12)
md <- data.frame(x1, x2, y1, y2) 

> head(md)

  x1 x2         y1         y2
1  A  E -1.4603164 -0.9662473
2  A  E -0.5247227  1.7970341
3  A  F  0.8990502  1.7596285
4  A  F -0.6791145  2.2900357
5  B  E  1.2894863  0.1152571
6  B  E -0.1981511  0.6388998


# aggregate by taking maximum of each unique (x1, x2) combination
md.agg <- with(md, aggregate(y1, by = list(x1, x2), FUN = max))
names(md.agg) <- c("x1", "x2", "y1")

>  md.agg 
  x1 x2         y1
1  A  E -0.5247227
2  B  E  1.2894863
3  C  E  0.9982510
4  A  F  0.8990502
5  B  F  2.5125956
6  C  F -0.5916491


# merge y2 into the aggregated data
md.final <- merge(md, md.agg)

> md.final

  x1 x2         y1         y2
1  A  E -0.5247227  1.7970341
2  A  F  0.8990502  1.7596285
3  B  E  1.2894863  0.1152571
4  B  F  2.5125956 -0.2217510
5  C  E  0.9982510  0.6813261
6  C  F -0.5916491  1.0348518

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM