Reputation: 363
This is my situation. I have a data.frame, let's say: DF <- data.frame(....)
Now I want to export this DF to SAS Transport file using SASxport::write.xport(DF, ...)
The function write.xport takes the name of a variable and uses it to name the SAS dataset. So the above code will result in SAS dataset with one table named "DF". OK. As far as good.
Now I want to wrap calling SASxport in another function which does some initial tasks.
fn <- function(DataFrame) {
.... do something ....
write.xport( DataFrame, .... )
}
fn(DF)
And now comes the problem. Resulting SAS dataset contains a table named "DataFrame", not "DF".
So, I tried to get the original name of a dataset and pass it somehow to write.xport:
fn <- function(DataFrame) {
.... do something ....
params <- as.list(match.call()[-1])
name <- as.character(params$DataFrame)
write.xport( eval(parse(text=name)), .... )
}
fn(DM)
But this doesn't work. It creates SAS file with invalid name (so it is NOT "DM" for sure), making the file unreadable by SAS. eval/substitute doesn't work as well (the name in SAS is then "eval_sub").
How can I pass the original name of data set, DF to this internal call of write.xport?
The code should fool the write.xport function, give her DF, not DataFrame, exactly as it would be done writing the code in the console manually.
Is this possible?
EDIT:
OK, eval(parse(text = paste0("write.xport(", name, .........")))
did the trick. It is solved now.
Upvotes: 1
Views: 95
Reputation: 206421
I suggest you try to avoid the eval()
function for situations like this. The best way would be to use the list=
parameter of the write.xport
function. using setNames()
, you can set whatever name you want for the object. Here i've also added a parameter called name=
where you can set any name you want, but it will default to the name of the variable passed to the function.
#test data
DF<-data.frame(a=1:10, b=letters[1:10])
library(SASxport)
fn <- function(DataFrame, name=deparse(substitute(DataFrame))) {
write.xport( list=setNames(list(DataFrame), name), file="test.dat")
}
fn(DF)
Upvotes: 2
Reputation: 363
OK, eval(parse(text = paste0("write.xport(", name, .........")))
did the trick. The SAS file is generated correctly and contains a table named as required. It is solved now.
Upvotes: 0