2015-12-16 24 views
1

有什么办法来transfrom以下SAS代码:使用R将表的代码类型“If ... Then ....”转换为表格?

If CRM = 50 then coefgpc=coefgpc * 1;      
    Else If CRM <= 54 then coefgpc=coefgpc * 1.12;      
    Else If CRM <= 59 then coefgpc=coefgpc * 1.245;      
    Else If CRM <= 99 then coefgpc=coefgpc * 1.609;      
    Else If CRM = 100 then coefgpc=coefgpc * 1.987;      
    Else If CRM >= 101 then coefgpc=coefgpc * 2.223; 

到表是这样的:

enter image description here

375来自另一个文件,它应该手动输入

回答

2

以下工作。

txt <- " If CRM = 50 then coefgpc=coefgpc * 1;      
     Else If CRM <= 54 then coefgpc=coefgpc * 1.12;      
     Else If CRM <= 59 then coefgpc=coefgpc * 1.245;      
     Else If CRM <= 99 then coefgpc=coefgpc * 1.609;      
     Else If CRM = 100 then coefgpc=coefgpc * 1.987;      
     Else If CRM >= 101 then coefgpc=coefgpc * 2.223;" 

#Split the string into workable blocks with regex 
splt <- strsplit(txt, split = "\n|\\*|=")[[1]] 

#Extract elements with numbers 
nos <- splt[grepl("[0-9]", splt)] 

#odd-numbered entries are your limits 
lims <- as.integer(gsub("[^0-9]", "", nos[seq(1, length(nos), by = 2)])) 
#even-numbered entries are your factors 
facts <- as.numeric(gsub("[^0-9.]", "", nos[seq(2, length(nos), by = 2)])) 

#wrap up into a 'data.frame' 
data.frame(lower = c(lims[1], lims[-length(lims)] + 1), 
      upper = c(lims[-length(lims)], 375L), 
      Factor = facts) 
+0

谢谢,在问题中编辑! – Metariat

+0

代码中的“\ n | \ * | =”是什么意思? – Metariat

+0

'|'分隔了我们分割文本的三个方面:由新行字符('\ n'),星号('\\ *')和等号('=') – MichaelChirico