簡體   English   中英

SAS中R中的等效宏代碼

[英]Macro code equivalent in R from SAS

這可能很簡單,所以提前道歉-我是R語言的新手。 我想將下面的SAS宏編碼為R中的函數(這是從內存中獲取的,因為我沒有SAS的外部工作):

%macro coalesce(x=);
proc sql;
create table test as select *
, coalescec(&x.1,&x.2) as &x 
from survey_results;
quit; 
%mend;
%coalesce(x=emp_stat)

到目前為止,我已經對此進行了編碼,但是在從一個x = emp_stat輸入觸發emp_stat1和emp_stat2時遇到了麻煩。 這可能嗎?

coalesce.func <- function(x) {
survey_results$x <- coalesce(survey_results$x1,survey_results$x2)
}

謝謝!

# create data
set.seed(21)
survey_results <- data.frame(a1 = sample(c(NA, 'q'), 10, T)
                             , a2 = sample(c(NA, 'w'), 10, T)
                             , stringsAsFactors = F)
survey_results
# #    a1 a2
# 1     q    w
# 2  <NA>    w
# 3     q <NA>
# 4  <NA>    w
# 5     q <NA>
# 6     q <NA>
# 7  <NA>    w
# 8  <NA> <NA>
# 9     q <NA>
# 10    q    w

library(dplyr) #loaded to use 'coalesce' function included in package
coalesce.fun <- function(x, df = survey_results){
  # call coalesce on the input x pasted to . and the vector 1 to 2
  # create data frame with it 
  # assign to 'out' 
  out <- data.frame(do.call(coalesce, df[paste0(x, 1:2)]))
  # set column names to input
  colnames(out) <- x
  # return 'out'
  out
}
test <- coalesce.fun('a')
# #     a
# 1     q
# 2     w
# 3     q
# 4     w
# 5     q
# 6     q
# 7     w
# 8  <NA>
# 9     q
# 10    q

如果要在R中具有等效的proc sql ,可以使用sqldf軟件包。 此功能應與上面的功能等效。

library(sqldf)
library(glue)

coalesce.fun <- function(x){
  sqldf(glue('
  select coalesce({x}1, {x}2) as {x}
  from survey_results
  '))
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM