[英]R: Custom function in apply()
first time user here! 初次使用者在这里! I'm just learning R and have what I hope is a simple question.
我只是在学习R,我希望有一个简单的问题。 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. pmax
是“并行化” maximun所以大于1由1代替任何值可能不工作过的[]
如果nums
是一个原子矢量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.