Apply User Defined Functions

2019-09-09 21:56发布

问题:

I have a user-defined function.

funct<-function(object,state){
  Init<-matrix(0,nrow=1,ncol=length(object))
  colnames(Init)<-unique(object)
  Init[,which(colnames(Init)==state)]<-Init[,which(colnames(Init)==state)]+1
  return(Init)
}

Show the function output

letters1<-letters[1:5]
funct(letters1,"b")

I have a data frame, and apply my function on it to combine it by rows by using apply family.

dat<-data.frame(letters1=c("a","b"))

My try on it

mapply(funct,unique(dat$letters1),dat$letters1)

Desired output

rbind(funct(unique(dat$letters1),"a"),funct(unique(dat$letters1),"b"))
 a b
[1,] 1 0
[2,] 0 1

Thanks.

回答1:

Probably calling diag would be a more elegant solution to get the "desired output" :)

But you can also simplify your custom function a bit, e.g.:

> dat <- c("a", "b")
> sapply(dat, function(x) as.numeric(dat == x))
     a b
[1,] 1 0
[2,] 0 1


标签: r apply