[R] passing a variable (containing the value of the argument) to a function
Spencer Graves
spencer.graves at pdf.com
Wed Oct 22 22:37:53 CEST 2003
Hi, Peter: I'll have to study your example and alternatives. spencer
graves
Peter Dalgaard wrote:
>Spencer Graves <spencer.graves at pdf.com> writes:
>
>
>
>>Hi, Peter: How does that compare with the following: for (myname
>>in names(myframe)[1:4]){
>> mdl <- formula(paste(myname, "~ etc.etc"))
>> myfit <- lm(mdl, data=myframe)
>> print(summary(myfit))
>>}
>>
>> Or: for (myname in names(myframe)[1:4]){
>> lm.txt <- paste("lm(", myname, "~ etc.etc, data=myframe)")
>> myfit <- eval(parse(text=lm.txt))
>> print(summary(myfit))
>>}
>>
>> You are teaching me new uses of "substitute", and I just wonder
>>about the relative advantages and disadvantages of the different
>>approaches. Thanks,
>> spencer graves
>>
>>
>
>Those variants should work (and similar code is all over the place in
>the modelling functions). I just tend to prefer to avoid going via the
>textual representation. There are a couple of devils lurking in there,
>in particular if a data frame has variables with "funny names" -
>spaces or special characters inside, for example.
>
>To wit:
>
>
>
>>myname <- "foo bar"
>>lm.txt <- paste("lm(", myname, "~ etc.etc, data=myframe)")
>>lm.txt
>>
>>
>[1] "lm( foo bar ~ etc.etc, data=myframe)"
>
>
>>parse(text=lm.txt)
>>
>>
>Error in parse(file, n, text, prompt) : parse error
>
>
>
>
More information about the R-help
mailing list