Domanda

I'm trying to use the apply function. I have a function called rowcosty():

rowcosty <- function(p,x,y){
    return (-1*y*log(hyp(p,x))-(1-y)*log(1-hyp(p,x)))
}

hyp <- function(p, input){
    return (sigmoid(p %*% input))
}

sigmoid <- function(y){
    return (1/(1 + exp(-y)))
}

In my example p is a vector of length 5000, x is a matrix with dimensions 5000 X 400 and y is also a vector of length 5000.

Now I want to apply the rowcosty() function to each row in x and then return a vector of length 5000 that includes the value returned by rowcosty() for each row.

I was successful doing this using a for-loop:

vec <- rep(0,5000)
for(i in 1:5000){
    vec[i] <- rowcosty(p,x[i,],y[i])
}

But this call of the apply() function yielded the error: "Error in -y * log(hyp(p, x)) : non-conformable arrays"

apply(x,1,rowcosty,p = p, y = y)

Can anybody please tell me what is going wrong here?

È stato utile?

Soluzione

When you are doing rowcosty(p,x[i,],y[i]), you are indirectly looping on two variables at the same time: x and y. apply, lapply, sapply, vapply all loop on a single variable.

mapply is the usual approach when looping on two or more variables. You can do:

mapply(rowcosty, split(x, row(x)), y, MoreArgs = list(p = p))

Or you can also loop on a single variable: the index i.

sapply(1:nrow(x), function(i) rowcosty(p,x[i,],y[i])) 
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top