简体   繁体   中英

R: Non-numeric argument to mathematical function

I have written a userdefined function:

epf <- function(z,x,noise=std_noise){
    z_dims <- length(z)
    std_noise <- 0.5*matrix(1,1,z_dims)
    std_noise <- as.data.frame(std_noise)

    obs_prob <- dnorm(z,x[1:z_dims],noise)

    error <- prod(cbind(1,obs_prob))
    return(error)
}

This function is called in a for-loop in another function:

w <- matrix(0,N,1)
        for (i in 1:N){
            w[i] <- epf(z,p[i,],R_noise) 
        }

where z is a 2-dimensional vector, N=1000 , p is a dataframe of 1000 observations and 4 variables and R_noise is a dataframe og 1 observation and 4 variables.

Here I get the error: "Non-numeric argument to mathematical function", for the line obs_prob <- dnorm(z,x[1:z_dims],noise)

Can anyone help me with finding the error?

I have looked through questions similar to mine, but I still can't find the error in my code.

Edit:
Added definition of N

dnorm(as.matrix(z), x[1:a_dims], noise) may work better.

And more broadly speaking, a data frame with one row and two columns may be better expressed as a vector. Data frames look like matrices and as you put it 'two-dimensional vectors', but they are different in important aspects.

The same error may be occurring because you are feeding dnorm a second data frame in its last argument noise by passing R_noise .

Also, consider that p[i, ] has four values. It is being subsetted by obs_prob with x[1:z_dims] . In this case, z_dims will equal 2 since length(z) is 2. So you are evaluating dnorm(data.frame(z), p[1, ][1:2], data.frame(R_noise)) .

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