function - parameter use in R -


scorekm <- function(km, x1,x2,x3,x4) {     data<-matrix(c(x1,x2,x3,x4),nrow=1)     k <- nrow(km$centers)     n <- nrow(data)     d <- as.matrix(dist(rbind(km$centers, data)))[-(1:k),1:k]     d <- matrix(d,nrow=1)     out <- apply(d, 1, which.min)     return(out) } 

this original function. there several parameters (not 4, maybe 8, 12,...), , every 4 unit. should use loop? in loop, how can reach parameter?and how know how many there are?

 scorekm <- function(km,x...){}  

function should this.

km<-kmeans(iris,3) scorekm<- function(km, x,...) { result=null for(i in 1:nargs()-1) { data<-matrix(c(args[[i+1]],args[[i+2]],args[[i+3]],args[[i+4]]),nrow=1) k <- nrow(km$centers) d <- as.matrix(dist(rbind(km$centers, data)))[-(1:k),1:k] d <- matrix(d,nrow=1) out <- apply(d, 1, which.min) result<-cbind(out,result) i<-i+4 } return(result)} 

i collect variables through ... so:

scorekm <- function(km, x, ...) {   x.args <- list(...)   out <- do.call("cbind", x.args)   out } 

notice naming argument, you're giving column name "as go".

> scorekm(km = 1, x = 2, x1 = runif(3), column2 = runif(3), variable3 = runif(3))             x1    column2 variable3 [1,] 0.2106436 0.07142857 0.6466394 [2,] 0.3684540 0.16306419 0.9937268 [3,] 0.5230319 0.66318683 0.3020110 

Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

c# - must be a non-abstract type with a public parameterless constructor in redis -

ajax - PHP/JSON Login script (Twitter style) not setting sessions -