简体   繁体   English

像SAS宏一样在R中导入数据

[英]Importing Data in R like SAS macro

In SAS, we can write macro for importing files. 在SAS中,我们可以编写用于导入文件的宏。 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? 有人可以帮我得到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. 用户定义的函数,用于读取指定的csv文件,对一列或多列应用某种格式,然后返回结果。 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. 以下代码像在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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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