简体   繁体   English

应用用户定义的功能

[英]Apply User Defined Functions

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. 我有一个数据框,并在其上应用函数,以通过使用Apply系列按行将其组合。

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. 谢谢。

Probably calling diag would be a more elegant solution to get the "desired output" :) 可能调用diag将是获得“所需输出”的一种更优雅的解决方案:)

But you can also simplify your custom function a bit, eg: 但是您也可以稍微简化自定义功能,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM