简体   繁体   中英

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!

我们可以使用replace

replace(nums, nums > 1, 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM