[R] Function on an array

Sven E. Templer sven.templer at gmail.com
Wed Oct 8 13:50:21 CEST 2014


Dear Barry,

some thoughts:

1) e in your function status_fnc is a vector when applied on a matrix
like object, but you index it as a matrix (e[,i] should be e[i]).
2) You can simplify the if statement by using the function any
(replacing all the OR statements) on the vector, so use any(e=='Y')
here.
3) sapply applies over a list, which your object isn't. You provide a
matrix (cbind), so you should use apply in that case.

So one solution might be:

ex1 <- c('Y', 'N', 'Y')
ex2 <- c('Y', 'N', 'Y')
ex3 <- c('N', 'N', 'Y')
ex4 <- c('N', 'N', 'Y')
status_fnc <- function(e){
  if (any(e=='Y'))
    return('Okay')
  else
    return('Not okay')
}
status <- apply(cbind(ex1, ex2, ex3, ex4), 1, status_fnc)
status

On 8 October 2014 12:54, Barry King <barry.king at qlx.com> wrote:
> ex1 <- c('Y', 'N', 'Y')
> ex2 <- c('Y', 'N', 'Y')
> ex3 <- c('N', 'N', 'Y')
> ex4 <- c('N', 'N', 'Y')
>
> status <- array(NA, dim=3)
>
> # I am trying to return 'Okay' if any of the values
> # in a column above is 'Y' but I am not constructing
> # the function corrrectly.  Any assistance is
> # greatly appreciated
>
> status_fnc <- function(e){
>   if (e[ ,1] == 'Y' | e[ ,2] == 'Y' | e[ ,3] == 'Y' | e[ ,4] == 'Y'){
>     return('Okay')
>   } else return('Not okay')
> }
> status <- sapply(cbind(ex1, ex2, ex3, ex4), status_fnc)
>
>         [[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.



More information about the R-help mailing list