J. Paul
J. Paul

Reputation: 391

R: Custom function in apply()

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!

Upvotes: 2

Views: 126

Answers (2)

IRTFM
IRTFM

Reputation: 263301

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.

Upvotes: 1

akrun
akrun

Reputation: 886948

We can use replace

replace(nums, nums > 1, 1)

Upvotes: 3

Related Questions