I have a situation where this is fine: > if (length(x)>15) { clever <- rr.ATM(x, maxtrim=7) } else { clever <- rr.ATM(x) } > clever $ATM [1] 1848.929 $sigma [1] 1.613415 $trim [1] 0 $lo [1] 1845.714 $hi [1] 1852.143 But this variant, using ifelse(), breaks: > clever <- ifelse(length(x)>15, rr.ATM(x, maxtrim=7), rr.ATM(x)) > clever [[1]] [1] 1848.929 What am I doing wrong? -- Ajay Shah Consultant ajayshah at mayin.org Department of Economic Affairs http://www.mayin.org/ajayshah Ministry of Finance, New Delhi
Ajay Narottam Shah wrote:> I have a situation where this is fine: > > > if (length(x)>15) { > clever <- rr.ATM(x, maxtrim=7) > } else { > clever <- rr.ATM(x) > } > > clever > $ATM > [1] 1848.929 > > $sigma > [1] 1.613415 > > $trim > [1] 0 > > $lo > [1] 1845.714 > > $hi > [1] 1852.143 > > But this variant, using ifelse(), breaks: > > > clever <- ifelse(length(x)>15, rr.ATM(x, maxtrim=7), rr.ATM(x)) > > clever > [[1]] > [1] 1848.929 > > What am I doing wrong?if (test) expr1 else expr2 evaluates only one of expr1 or expr2 according to test, and returns that result. ifelse(test, expr1, expr2) executes all three of test, expr1, and expr2, and puts together a vector response where for each element of test that is true (non-zero), the corresponding element of one of the expr's is selected. I'd guess your x is length 1, so your test is length 1, and only the first element of the result of rr.ATM is returned (which is not very useful). To get what you want, you should write clever <- if(length(x) > 15) rr.ATM(x, maxtrim=7) else rr.ATM(x); Duncan Murdoch
This is working exactly as documented. Nothing `breaks'! What does the help page say? 'ifelse' returns a value with the same shape as 'test' which is filled with elements selected from either 'yes' or 'no' depending on whether the element of 'test' is 'TRUE' or 'FALSE'. 'test' is of length one and true, so you got the first element of 'yes', which is a list as the first (and only) element of the answer. On Tue, 12 Jul 2005, Ajay Narottam Shah wrote:> I have a situation where this is fine: > > > if (length(x)>15) { > clever <- rr.ATM(x, maxtrim=7) > } else { > clever <- rr.ATM(x) > } > > clever > $ATM > [1] 1848.929 > > $sigma > [1] 1.613415 > > $trim > [1] 0 > > $lo > [1] 1845.714 > > $hi > [1] 1852.143 > > But this variant, using ifelse(), breaks: > > > clever <- ifelse(length(x)>15, rr.ATM(x, maxtrim=7), rr.ATM(x)) > > clever > [[1]] > [1] 1848.929 > > What am I doing wrong?-- Brian D. Ripley, ripley at stats.ox.ac.uk Professor of Applied Statistics, http://www.stats.ox.ac.uk/~ripley/ University of Oxford, Tel: +44 1865 272861 (self) 1 South Parks Road, +44 1865 272866 (PA) Oxford OX1 3TG, UK Fax: +44 1865 272595