根据另一个值的值从列变量子集值的范围

时间:2018-07-26 19:16:42

标签: r range subset

我正在尝试将所有行保留在数据框中,但是请删除2行,但至少要保留2年的8行。

library(tidyverse)   

forms <- data_frame( CASEID = rep(01012,5), VISIT = c(450, 450, 365, 365, 450), FORM = c(18, 8, 7, 2, 2), DTYvisit = c(2006, 2006, 2003, 2003, 2006) )

> forms # A tibble: 5 x 4

CASEID VISIT FORM YEAR   

<dbl> <dbl> <dbl> <dbl>   

1 1012 450 18 2006

2 1012 450 8 2006

3 1012 365 7 2003

4 1012 365 2 2003

5 1012 450 2 2004

6 1013 450 8 2003

7 1013 450 18 2003

8 1013 450 2 2003

9 1012 450 2 2009

关于如何丢弃不在FORM 8 DTyvisit的<2年范围内的FORM 2行的任何建议?

效果很好:

form2.matchedOnForm8 <- forms %>% group_by(CASEID) %>% filter(FORM == 8) %>% select(CASEID, VISIT, DTYvisit) %>% left_join(filter(forms, FORM == 2), by = c("CASEID", "VISIT", "DTYvisit")) %>% bind_rows(filter(forms, FORM != 2))

但是现在我正在失去观察力。

我需要以下内容:

library(tidyverse)

forms <- data_frame( CASEID = rep(01012,5), VISIT = c(450, 450, 365, 365, 450), FORM = c(18, 8, 7, 2, 2), DTYvisit = c(2006, 2006, 2003, 2003, 2006) )

> forms # A tibble: 5 x 4

CASEID VISIT FORM YEAR   

<dbl> <dbl> <dbl> <dbl>

1 1012 450 18 2006

2 1012 450 8 2006

3 1012 365 7 2003

4 1012 450 2 2004

5 1013 450 8 2003

6 1013 450 18 2003

7 1013 450 2 2003

1 个答案:

答案 0 :(得分:1)

这是一个使用outer来计算给定的YEAR和FROM 8可能具有的所有YEAR值之间的差的解决方案。

min(abs(as.numeric(outer(df[df$FORM==8,'YEAR'],df[1,'YEAR'],'-'))))
[1] 0

df$diff <- apply(df, 1, function(x) min(as.numeric(outer(df[df$FORM==8,'YEAR',drop=TRUE],as.numeric(x['YEAR']),'-'))))

library(dplyr)
df %>% group_by(CASEID) %>% 
       filter(!(FORM==2 & abs(diff)>2))


df <- read.table(text="
    CASEID VISIT FORM YEAR   

                           1 1012 450 18 2006

                           2 1012 450 8 2006

                           3 1012 365 7 2003

                           4 1012 365 2 2003

                           5 1012 450 2 2004

                           6 1013 450 8 2003

                           7 1013 450 18 2003

                           8 1013 450 2 2003

                           9 1012 450 2 2009
                             ",header=T, stringsAsFactors = F)