简体   繁体   中英

Importing Data in R like SAS macro

In SAS, we can write macro for importing files. The macro can be of the form:

%MACRO IMPORT_Data(OUT = , FILE = );

        data &OUT ;  
           infile "&INPUT_path.\&File" 
           delimiter = ',' MISSOVER DSD lrecl=32767
           firstobs=2 ;

           input 
              Var1 : $10.
              Var2 : best12.
              Var3 : Percent5.2
              Var4 
              Var5 


           ;
%mend;

Once we have this macro, we just need to change the filename, and run the macro. We don't need to write the import file syntax everytime we read the file. Can anybody help me to get the version in R? A reference is also greatly appreciated.

You are looking for a function. A user defined function to read a specified csv file, apply some formatting to one or more of the columns, and return the result. Here is one example:

import_macro <- function(file, ...) {
data <- read.csv(file, ...)
# do whatever formatting you need to do. e.g.
data$v1 <- as.numeric(data$var1)
# var1 should be a column in your csv otherwise change it to something else
return(data)
}

Then you just run:

my_data <- import_macro('~/Desktop/file.csv', header = TRUE)

The following code helps me to read the data as we do in SAS. But I can't able to format my data here. So, putting the answer to get some useful comments.

imp<-strmacro(df,var,expr={df<-read.csv("C:\\Users\\RAW_DATA\\var.csv")})

mydata<-imp(mydata,"Import_data")  /* Data set file name*/
View(mydata)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM