R减去相同ID的值(从显示的第一个ID中减去) [英] R subtract value for the same ID (from the first ID that shows)

查看:122
本文介绍了R减去相同ID的值(从显示的第一个ID中减去)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个与这里发现的问题类似的问题:
R,从上一行中减去值,然后按分组(稍作修改;请参见下文):

I have a similar question to the question found here: R, subtract value from previous row, group by (slight modification; see below):

在R中,可以说我有此数据。 / p>

In R, lets say I have this data.

Data
id      date        value
2380    10/30/12    21.01
2380    10/31/12    22.04
2380    11/1/12     22.65
2380    11/2/12     23.11
20100   10/30/12    35.21
20100   10/31/12    37.07
20100   11/1/12     38.17
20100   11/2/12     38.97
20103   10/30/12    57.98
20103   10/31/12    60.83 

我想从相同ID的ID值中减去该值。我希望这是有道理的。见下文:)

And I want to subtract the value from the value of the ID of the same ID. I hope this makes sense. See below :)

id      date        value   diff
2380    10/30/12    21.01   0
2380    10/31/12    22.04   1.03
2380    11/1/12     22.65   1.64
2380    11/2/12     23.11   2.10
20100   10/30/12    35.21   0
20100   10/31/12    37.07   1.86
20100   11/1/12     38.17   2.96
20100   11/2/12     38.97   3.76
20103   10/30/12    57.98   0
20103   10/31/12    60.83   2.85

感谢您的帮助!

推荐答案

假设日期已经排序。我可能会检索每个id的第一个值,然后使用它来计算diff功能。
这样的事情。

Let's assume that dates are already sorted. I would probably retrieve the first value for each id and then use this to compute the diff feature. Something like this.

my.df <- data.frame(
  id = c(2380, 2380, 2380, 2380, 20100,20100,20100, 20100, 20103, 20103),
  date = c("10/30/12", "10/31/12", "11/1/12", "11/2/12", "10/30/12", "10/31/12", "11/1/12", "11/2/12", "10/30/12", "10/31/12"),
  value = c(21.01, 22.04, 22.65, 23.11, 35.21, 37.07, 38.17, 38.97, 57.98, 60.83),
  stringsAsFactors = F)
#
# get ids
my.ids <- unique(my.df$id) # or levels(my.df$id)

# get first val (assuming sorting by date)
id.val0 <- sapply(my.ids, (function(id){
  my.df$value[my.df$id == id][1]
}))
names(id.val0) <- my.ids

# do operation
my.df$diff <- sapply(1:nrow(my.df), (function(i){
  tmp.id <- my.df$id[i]
  my.df$value[i] - id.val0[as.character(tmp.id)]
}))

这篇关于R减去相同ID的值(从显示的第一个ID中减去)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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