过滤,子集或选择数据帧中不同时间条目的重复ID

时间:2017-08-20 20:21:46

标签: r dataframe ggplot2 dplyr

我有一些时间序列数据,其中包含一些时间指数的值,但没有其他时间指数。 我需要一种方法来过滤两个时间指数中出现的所有观察结果

这是一个可重现的例子,说明了我的问题。在最终的图表中,我只想要观察 Type == a ,这两个时间指数都会出现。

set.seed(1005)
mydat <- data.frame(
  ID = c('a1', 'a2', 'a3', 'a4', 'a5', 'a1', 'a2', 'a5', 'a12', 'a13'),
  Year = c(2000, 2000, 2000, 2000, 2000, 2001, 2001, 2001, 2001, 2001),
  Result = rnorm(10, mean = 20, sd = 10),
  Type = c('a','a','b','b','a', 'a', 'a', 'a', 'b', 'b'))

mydat %>% 
  ggplot(aes(x = Year, y = Result)) +
  geom_point(aes(color = Type)) + 
  geom_line(aes(group = ID))

enter image description here

注意:我还应该提到原始数据集中不存在 Type 列。我使用Type列创建了这个玩具数据集,以显示我想要用蓝色删除的点。

解决方案应独立于Type列,或者显示如何生成Type列而不对其进行硬编码。

1 个答案:

答案 0 :(得分:1)

你可以找到,好的让我们称它们重复,重复两次条目的ID并将它们标记为type == a

使用reshape

您可以将数据重新整形为 wide 格式,并删除NA的数据,这意味着它们没有两个时间条目的数据。看下面:

mydat_a <- reshape(mydat, idvar = "ID", timevar = "Year", direction = "wide")

mydat_a #Those with NA are the ones that you set them as Type == b


#     ID Result.2000 Result.2001 
# 1   a1    14.39524   37.150650 
# 2   a2    17.69823   24.609162 
# 3   a3    35.58708          NA 
# 4   a4    20.70508          NA 
# 5   a5    21.29288    7.349388 
# 9  a12          NA   13.131471 
# 10 a13          NA   15.543380

#Add the types again
mydat_a$Type <- "a"
mydat_a[which(is.na(mydat_a), arr.ind=TRUE)[,1],]$Type <- "b"

#go back to long format
mydat_a <- reshape(mydat_a, direction="long", 
                   varying=list(names(mydat_a)[2:3]), v.names="Result", 
                   idvar="ID", timevar="Year", times=2000:2001)

 #remove NA
 mydat_a <- na.omit(mydat_a)

您可以在下方查找最终的绘图解决方案(在mydat_a语法中使用mydat代替ggplot

或者...

mydat$Type <- "b" #make all of them "b" later change the repeated ones to "a"
mydat[  mydat$ID %in% mydat[mydat$Year==2000,]$ID
      & mydat$ID %in% mydat[mydat$Year==2001,]$ID,]$Type <- "a"
mydat$Type <- as.factor(mydat$Type)


mydat


#     ID Year   Result type 
# 1   a1 2000 17.67485    a 
# 2   a2 2000 15.16812    a 
# 3   a3 2000 27.18261    b 
# 4   a4 2000 14.18510    b 
# 5   a5 2000 32.91164    a 
# 6   a1 2001 13.30867    a 
# 7   a2 2001 20.15258    a 
# 8   a5 2001 31.21311    a 
# 9  a12 2001 32.62673    b 
# 10 a13 2001  6.85111    b

它为您提供了您在此处手动输入的类型。

然后您可以使用@d.b's solution

ggplot(data = split(mydat, mydat$Type)$a, aes(x = Year, y = Result)) + 
       geom_point(aes(color = Type)) + geom_line(aes(group = ID))

enter image description here

<强> 数据:

set.seed(123)
mydat <- data.frame(ID = c('a1', 'a2', 'a3', 'a4', 'a5', 'a1', 'a2', 'a5', 'a12', 'a13'),
                    Year = c(2000, 2000, 2000, 2000, 2000, 2001, 2001, 2001, 2001, 2001),
                    Result = rnorm(10, mean = 20, sd = 10))