On Feb 14, 2012, at 2:32 PM, Stavros Macrakis wrote:
That won't work because R has special rules for evaluating things in
the
function position. Examples:
*OK*
min(1:2)
"min"(1:2)
f<-min; f(1:2)
do.call(min,list(1:2))
do.call("min",list(1:2)) # do.call converts string->function
*Not OK*
("min")(1:2) # string in function position is not
converted
f<-"min"; f(1:2) # ditto
f<- c("min","max"); f[1](1:2) # ditto
What you need to do is make 'f' a list of *function values, *not a
vector
of strings:
f<- c(min,max)
and then select the element of f with [[ ]] (select one element),
not [ ]
(select sublist):
f[[1]](1:2)
Thus your example becomes
type <- c(min,max)
n <- 1:10
for (a in 1:2) {
print(type[[a]](n)) }
Another (uglier) approach is with do.call:
type <- c("min","max")
n <- 1:10
for (a in 1:2) {
print(do.call(type[a],list(n))) }
This is somewhat less ugly:
funs <- c("min","max")
for (a in funs) {
print(do.call(a, list(n))) }
[1] 1
[1] 10
Does that help?
-s
On Tue, Feb 14, 2012 at 14:02, Muhammad Rahiz
<muhammad.ra...@ouce.ox.ac.uk>wrote:
Hi all,
I'm trying to get the min and max of a sequence of number using a
loop
like the folllowing. Can anyone point me to why it doesn't work.
Thanks.
type <- c("min","max")
n <- 1:10
for (a in 1:2) {
print(type[a](n)) }
--
Muhammad
______________________________**________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/**listinfo/r-help<https://stat.ethz.ch/mailman/listinfo/r-help
>
PLEASE do read the posting guide http://www.R-project.org/**
posting-guide.html <http://www.R-project.org/posting-guide.html>
and provide commented, minimal, self-contained, reproducible code.
[[alternative HTML version deleted]]
______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
David Winsemius, MD
West Hartford, CT
______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.