【问题标题】:simple [SAS] macro in [R], how?[R] 中的简单 [SAS] 宏,怎么样?
【发布时间】:2018-07-27 13:40:00
【问题描述】:

我有名为 example1、example2、example3、example4 的数据集,其中工作库中的变量是 SEX(1 或 2) 我通过在 SAS 中使用 MACRO 将名为 exampleS1、exampleS2、exampleS3、exampleS4 的数据集限制为 SEX=1

喜欢这样。

%macro ms(var=);
data exampleS&var.;

set example&var.; IF SEX=1;
run; 
%mend ms;%ms(var=1);%ms(var=2);%ms(var=3);%ms(var=4);

现在,我想在 R 中完成这项工作 对我来说,在 R 中做到这一点并不容易。我该怎么做? (假设 example1,example2,example3,example4 是 data.frames)

提前谢谢你。

【问题讨论】:

    标签: r macros sas


    【解决方案1】:

    在名称中包含带有数字索引的变量是一件非常 SAS 的事情,一点也不像 R。如果您在 R 中有相关的 data.frames,则将它们保存在列表中。有很多方法可以将许多文件读入列表(请参阅here)。所以说你有一个 data.frames 列表

    examples <- list(
        data.frame(id=1:3, SEX=c(1,2,1)),
        data.frame(id=4:6, SEX=c(1,1,2)),
        data.frame(id=7:9, SEX=c(2,2,1))
    )
    

    然后你可以得到所有的 SEX=1 值

    exampleS <- lapply(examples, subset, SEX==1)
    

    然后您使用

    访问它们
    exampleS[[1]]
    exampleS[[2]]
    exampleS[[3]]
    

    【讨论】:

    • 其实这也不是一个非常高效的 SAS 解决方案 :)
    • @Reeza Ha。很高兴知道。我的 SAS 有点生锈了。你会在 SAS 中也使用某种集合类型吗?
    • 我可能会建议全部堆叠并立即过滤。 data want; set examples1-examples4; where sex=1; run; 这将堆叠所有数据并立即过滤。有几种方法可以简化 SET 语句的引用列表。
    【解决方案2】:

    你应该用 R 方式编程 R,而不是 SAS 方式,因为这会导致无尽的痛苦。 SAS-macro-language 和 R 不混合 imo,但这就是:

     # create example df's
     for (i in 1:4) {
       assign(paste0("example", i), data.frame(sex = sample(0:1, 10, replace = T)))
     }
     example1; example2; example3; example4
    
     # filter and store result in a list of df's
     l <- list(example1 = example1, example2 = example2, example3 = example3, example4 = example4)
     want <- lapply(l, function(x) subset(x, sex == 1))
     want$example1; want$example2; want$example3; want$example4 # get list of data frames
     # almost certainly what you should do
    
     # in principle possible to this too, but advise against it
     list2env(lapply(l, function(x) subset(x, sex == 1)), .GlobalEnv)
     example1; example2; example3; example4
    

    【讨论】:

    • 这与宏解决方案不一致,因为您几乎需要提前知道数据集的数量,请注意几个地方的硬编码 4。 SAS 不需要提前了解这些知识。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-16
    • 2014-02-21
    • 2019-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多