R中的数据转换“proc transpose”等价

时间:2018-02-13 19:29:54

标签: r medical

大家好,我是新来的,我有以下数据集

member_id<-c(603,603,603)
fill_date<-c("02/17/2005","06/13/2005","08/11/2005")
drug<-rep("a",3)
days_supply<-rep(30,3)
dataset<-data.frame(member_id,fill_date,drug,days_supply)

我希望将数据转换为以下内容: Transformed data

在sas我使用这段代码:

    proc sort data=claims;
       by member_id fill_dt;
       run;
    proc transpose data=claims out=fill_dates (drop=_name_) prefix=fill_dt;
    by member_id;
    var fill_dt;
    run;

    proc transpose data = claims out=days_supply (drop=_name_) prefix = days_supply;
    by member_id;
    var days_supply;
    run;

    data both;
    merge fill_dates days_supply;
    by member_id;
    format start_dt end_dt mmddyy10.;
    start_dt=fill_dt1;
    end_dt=fill_dt1+179;
    run;

我想知道你是否可以帮助R

中的等效代码

由于

2 个答案:

答案 0 :(得分:0)

这不是一个直接的答案,但是Hadley在tidyr github问题中提供了这些例子。 https://github.com/tidyverse/tidyr/issues/149

他与SO问题的联系: http://stackoverflow.com/questions/24929954; http://stackoverflow.com/questions/27247078

答案 1 :(得分:0)

这可能会让你入门。

# in case you don't have those packages installed
install.packages("reshape2")
install.packages("tidyverse")

library(reshape2)
library(tidyverse)


member_id<-c(603,603,603)
fill_dt<- c("2005-02-17", "2005-06-13", "2005-08-11")
days_supply<-rep(30,3)
dataset<-data.frame(member_id,fill_dt,days_supply)




dataset_melt <- melt( data =dataset, id.vars = "member_id" )
dataset_melt <- dataset_melt %>% group_by(variable) %>% mutate( variable_n = paste0( variable, row_number() ))

dataset_cast <- data.table::dcast( data = dataset_melt, formula = member_id ~  variable_n, value.var =c("value")  )
dataset_cast <- dataset_cast %>% mutate( start_dt = as.Date(fill_dt1), 
                                         end_dt   = start_dt + 179 )

dataset_cast

为了获得更好的帮助,我建议您创建一个最低限度可重复的SAS示例。这意味着SAS代码在SAS中创建数据,并创建所需的输出。您的数据并不是最小的,因为您没有使用&#34;药物&#34;变量。