像SAS宏一样在R中导入数据 [英] Importing Data in R like SAS macro
本文介绍了像SAS宏一样在R中导入数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在SAS中,我们可以编写用于导入文件的宏.宏的格式可以为:
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;
一旦有了这个宏,我们只需要更改文件名,然后运行宏即可.我们不需要在每次读取文件时都编写导入文件语法.有人可以帮助我在R中获得版本吗?参考也非常感激.
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.
推荐答案
您正在寻找一个函数.用户定义的函数,用于读取指定的csv
文件,对一列或多列应用某种格式,然后返回结果.这是一个示例:
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)
}
然后您就可以运行:
my_data <- import_macro('~/Desktop/file.csv', header = TRUE)
这篇关于像SAS宏一样在R中导入数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文