我有一份有几千张记录的数据。我的数据看起来是这样的:
Row ID OBS Dist_cover
1 2 1 60
2 2 0 140
3 2 0 15
4 2 0 147
5 2 0 37
6 2 0 89
7 3 1 239
8 3 0 62
9 3 0 11
10 3 0 193我需要在"1“和"0”值之间的Dist_cover中找到OBS差值.但按id分类。本质上,我在寻找1,4-2,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4有什么想法吗?
发布于 2018-06-20 02:54:07
您想要的可以用ave完成,按ID分组Dist_cover。
请注意,虽然这个问题说明应该按OBS进行分组,但实际上并不需要这样做。等于1的OBS总是第一个,就像问题中(隐式)指出的那样。“任择议定书”要求“1,4 - 2,4,4,4,4,4,4,4,4,4,4等的差额”。
ave(dat$Dist_cover, dat$ID, FUN = function(x) x - x[1])
#[1] 0 80 -45 87 -23 29 0 -177 -228 -46数据.
dat <-
structure(list(Row = 1:10, ID = c(2L, 2L, 2L, 2L, 2L, 2L, 3L,
3L, 3L, 3L), OBS = c(1L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L),
Dist_cover = c(60L, 140L, 15L, 147L, 37L, 89L, 239L, 62L,
11L, 193L)), .Names = c("Row", "ID", "OBS", "Dist_cover"), class = "data.frame", row.names = c(NA,
-10L))发布于 2018-06-20 03:05:38
按'ID‘分组后,子集'Dist_cover’其中'OBS‘为1(假设每个ID只有一个实例1),从’Dist_ filter‘中减去它,并filter 'OBS’值为0。
library(dplyr)
df1 %>%
group_by(ID) %>%
mutate(Diff = Dist_cover[OBS==1] - Dist_cover) %>%
# if OBS is 1 occurs always as the first observation for ID
# mutate(Diff = first(Dist_cover) - Dist_cover) %>%
filter(OBS == 0)数据
df1 <- structure(list(Row = 1:10, ID = c(2L, 2L, 2L, 2L, 2L, 2L, 3L,
3L, 3L, 3L), OBS = c(1L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L),
Dist_cover = c(60L, 140L, 15L, 147L, 37L, 89L, 239L, 62L,
11L, 193L)), .Names = c("Row", "ID", "OBS", "Dist_cover"),
class = "data.frame", row.names = c(NA,
-10L))https://stackoverflow.com/questions/50939428
复制相似问题