首页 > 解决方案 > proc排序,保留在R中

问题描述

在 R 中如何 first.variable 和 retain 工作。

df <- data.frame(inst = c('a', 'a', 'a','a','b', 'b', 'b','b'), 
                 sample = c('pa', 'pa', 'pc','pc', 'pa', 'pa', 'pc','pc'),
                 testdate = c("04/29/2019","04/30/2019", "04/29/2019","04/30/2019", "04/29/2019","04/30/2019", "04/29/2019","04/30/2019"), 
                 run = c(1,2,1,2,1,2,1,2))


proc sort data=c1; by inst sample testdate; run;
data c1;
    set c1;
    by inst sample testdate;
    if first.sample then day=0;
    if first.testdate then day+1;
run;

在每个 inst 和 sample 中,day 列应该是 1,2。

标签: rsas

解决方案


这是一个例子。仅供参考 - 将来请显示示例数据,您期望的输出以及您迄今为止尝试过的内容。

library(tidyverse)

#adds in dataset

mpg<-mpg

#Add group counter where each year has the same group number

#within each manufacture/model combination

mpg2 <- mpg %>%
    #grouping variables (testdate would not be in your list)
    group_by(manufacturer, model) %>%
    mutate(day = row_number(), run = cumsum(c(TRUE, year[-1] != year[-n()]))))

推荐阅读