Skip to content

an apply question

4 messages · m p, Jorge I Velez, arun +1 more

#
HI,
Assuming a matrix:
set.seed(15)
mat1<-matrix(sample(-10:10,40,replace=TRUE),ncol=5)
apply(mat1,2,function(x) ifelse(x<0,x+24, x))
?# ?? [,1] [,2] [,3] [,4] [,5]
#[1,]??? 2??? 4?? 23??? 1??? 0
#[2,]?? 18??? 7?? 10??? 3?? 16
#[3,]?? 10?? 16?? 16?? 16??? 0
#[4,]??? 3??? 3??? 6?? 17??? 3
#[5,]?? 21??? 0??? 6??? 9?? 16
#[6,]?? 10??? 4??? 6??? 0??? 0
#[7,]??? 7??? 8?? 21??? 0?? 20
#[8,]?? 19??? 7?? 15?? 19??? 5
A.K.




----- Original Message -----
From: m p <mzp3769 at gmail.com>
To: r-help at stat.math.ethz.ch
Cc: 
Sent: Saturday, January 19, 2013 12:17 AM
Subject: [R] an apply question

Hello,
It should be easu but I cannot figure out how to use apply function. I am
trying to replace negative values in an array with these values + 24.
Would appreciate help. Thanks,
Mark

shours <- apply(fhours, function(x){if (x < 0) x <- x+24})
Error in match.fun(FUN) : argument "FUN" is missing, with no default

??? [[alternative HTML version deleted]]

______________________________________________
R-help at 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.
#
On Jan 18, 2013, at 9:17 PM, m p wrote:

            
Unless this is a homework question then using `apply` seems inefficient.
You should not use the assignment operator in the expression that  
forms the consequent for `ifelse`. (Furthermore apply takes three  
arguments and you only have two.)

Vectorize:

mat1<-matrix(sample(-10:10,40,replace=TRUE),ncol=5)

  mat1[mat1 < 0] <- mat1[mat1 < 0]+24
  mat1
      [,1] [,2] [,3] [,4] [,5]
[1,]    2    4   23    1    0
[2,]   18    7   10    3   16
[3,]   10   16   16   16    0
[4,]    3    3    6   17    3
[5,]   21    0    6    9   16
[6,]   10    4    6    0    0
[7,]    7    8   21    0   20
[8,]   19    7   15   19    5
David Winsemius, MD
Alameda, CA, USA