[R] how to apply a self-written function to a data frame

Richard.Cotton at hsl.gov.uk Richard.Cotton at hsl.gov.uk
Mon Jul 6 18:17:30 CEST 2009


> I have written a function in order to analyse gaze paths. It works 
> with the test data but when I try to apply the function to a data 
> frame that stores "the real data" in columns I receive the error 
> message that the 
> 
> " In if (pp > 1) { :
>   condition has length > 1 only the first element will be used
> "

This means that pp is a vector (and hence pp > 1 is also a vector), but 
'if' requires a scalar logical value.  Try, e.g.
if(1:10 > 5) message("foo")
for a simpler way of recreating this error message.

> I interpret this error message as saying that only the first element
> of pp is used. However, I'd like to analyse each row of the data 
> frame, row by row. Using 
> 
> apply(final, 1, abst, gx,gy,tx,ty,p_pos) (with gx - p_pos being 
> columns of the data frame final) 

By the looks of things, when you call apply(final, 1, abst, 
gx,gy,tx,ty,p_pos), the value of pp (inside the abst function) is being 
taken as the value of p_pos, which is all the relevant columns of the data 
frame.  Are you sure that this is the value you meant for pp?

There is a vectorised version of if, namely the ifelse function.  Perhaps 
the line if (pp > 1) {px = -px } should be
px <- ifelse(pp > 1, -px, px)

or even more simply, 
px[pp > 1] <- -px[pp > 1]

Regards,
Richie.

Mathematical Sciences Unit
HSL


------------------------------------------------------------------------
ATTENTION:

This message contains privileged and confidential inform...{{dropped:20}}




More information about the R-help mailing list