2

first time user here! I'm just learning R and have what I hope is a simple question. I have an array of numbers, nums, and I would to ensure no number is greater than one. I'm trying to do

myfct <- function(x) {
  if ( x > 1.0 ) x = 1.0
  return(x)
}
apply(nums, 1, myfct)

But I then get this error

Error in apply(nums, 1, myfct) : 
dim(X) must have a positive length

What am I doing wrong and is there a better way to do it? Thanks!

J. Paul
  • 391
  • 1
  • 4
  • 14
  • Welcome to SO! `apply` can be used only on matrices and arrays, and it looks like your `nums` is just a vector. Look at `sapply` and `lapply`. Second, though, for this and future questions, you will have a much better answer rate (greater than 0) if you first read about [minimum](http://stackoverflow.com/help/mcve) and [reproducible questions](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – r2evans Jun 17 '16 at 05:54
  • It seems that `nums` is a vector. So you can directly apply the `myfct` i.e `myfct(nums)` with changes in `myfct` like changing `if` to `ifelse` – akrun Jun 17 '16 at 05:54
  • 5
    pmin(x, 1) or x[x > 1] <- 1 – Roland Jun 17 '16 at 05:57
  • I didn't realize the difference between array and vector; I assumed they were the same! Sapply works as I thought apply would. Thanks r2evans and akrun! – J. Paul Jun 17 '16 at 06:07
  • Roland's solution also works as I would like. Thanks! – J. Paul Jun 17 '16 at 06:07

2 Answers2

3

We can use replace

replace(nums, nums > 1, 1)
akrun
  • 874,273
  • 37
  • 540
  • 662
1

Try this instead:

 nums[] <- pmin(nums, 1)

pmax is a "parallelized" maximun so any values greater than 1 are replaced by 1. Might have worked without the [] if nums was an atomic vector.

IRTFM
  • 258,963
  • 21
  • 364
  • 487
  • This seems to do the opposite of what I want, in that all values below 1 are then set to 1. I think the pmin solution is what will work in this particular case. This newbie appreciates the help regardless! – J. Paul Jun 17 '16 at 06:18