如何在整个数据框中调用“fun”函数。我正在尝试使用do.call。有什么想法吗?
fun<-function(x,y,z){
if(x == "a"){
return(paste("first",y,z))
}else if(x == "b"){
return(paste("second",y,z))
}else
{
return(paste("thrid",y,z))
}
}
d1<-c("a","b","c")
d2<-c("b","b","c")
d3<-c("c","b","c")
dat<-data.frame(d1,d2,d3)
colnames(dat)<-c("header1","header2","header3")
fun("b","b","c") #here is an example of the function call
#now I want to call the fundtion on the data frame and put it in a new column
dat$newcolumn<- do.call(fun,dat$header1, dat$header2,dat$header3 )
#results should be
"first b c"
"second b c"
"third b c"
与
相同fun(dat$header1[1],dat$header2[1],dat$header3[1])
fun(dat$header1[2],dat$header2[2],dat$header3[2])
fun(dat$header1[3],dat$header2[3],dat$header3[3])
但我想do.call为我做这件事。
答案 0 :(得分:1)
你非常接近,在每一行上使用apply都可以解决问题:
apply(dat,1,function(u) fun(u[1],u[2],u[3]))
但是,根据函数的定义,结果应为:
[1] "first b c" "second b b" "thrid c c"
如果您想要撰写的结果,只需重新定义您的数据框:
dat = as.data.frame(t(dat))
由于您需要do.call
的示例:
var = "fun"
apply(dat,1,function(u) do.call(var, list(u[1],u[2],u[3])))