我有一个数据框:
smoke <- matrix(c(51,43,22,92,28,21,68,22,9),ncol=3,byrow=TRUE)
colnames(smoke) <- c("High","Low","Middle")
smoke=as.data.frame(smoke);smoke$sit[1]="bit"; smoke$sit[2]="bsa"
smoke$sit[3]="bu"
smoke
High Low Middle sit
1 51 43 22 bit
2 92 28 21 bsa
3 68 22 9 bu
我想申请我的简单功能:
myf<- function(c,r){
x=5*c+r
write.table(x,paste0("res_", r, "_", c, ".txt"))}
res=apply(smoke[,c('Low','High')], 1, function(x) myf(x[1],x[2]))
这适用于fine.output res_51_43.txt .......
现在我只想将smoke$sit
中的相应名称添加到输出文本文件中。期望的输出res_bit_51_43.txt .......
myf<- function(t,c,r){x=5*c+r
write.table(x,paste0("res_", t, r, "_", c, ".txt"))}
res=apply(smoke[,c('Low','High','sit')], 1, function(x) myf(x[1],x[2],x[3]))
我收到了这个错误:
Error in 5 * c : non-numeric argument to binary operator
答案 0 :(得分:1)
这是一个使用lapply和split的示例。注意:我已修改您的函数以返回文件名。
myf<- function(c,r,t){
x=5*c+r
myfile <- paste0("res_", t, r, "_", c, ".txt")
return(myfile)
}
res=lapply(split(smoke[,c('Low','High','sit')],1:nrow(smoke)),
FUN=function(x) myf(c=x[1],r=x[2],t=x[3]))
> res
$`1`
[1] "res_bit51_43.txt"
$`2`
[1] "res_bsa92_28.txt"
$`3`
[1] "res_bu68_22.txt"