外部函数错误使用包括数据框引用的函数

时间:2017-12-03 06:47:38

标签: r

我试图使用外部功能获取3D表面。我定义的函数引用data.frame中的列。以下是可重现的简要代码。

test.txt是

   a    b   c
   1    0   0 
   2    0   0
   3    0   0
   6    0   0
   4    0   0

和代码是

test<- read.table(file="test.txt",header=TRUE)

testf<-function(q,w){
test$b<-q
test$c<-w
sum(test$b)+sum(test$c)
}

x<-seq(1,10,by = 1)
y<-seq(0,30,by = 1)

z<-outer(x,y,testf)

结果显示为错误

Error in `$<-.data.frame`(`*tmp*`, "b", value = c(1, 2, 3, 4, 5, 6, 7,  : 
replacement has 310 rows, data has 5 

5.stop(sprintf(ngettext(N, "replacement has %d row, data has %d", 
"replacement has %d rows, data has %d"), N, nrows), domain = NA) 

4.`$<-.data.frame`(`*tmp*`, "b", value = c(1, 2, 3, 4, 5, 6, 7, 
8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 
8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 
8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7,  ... 

3.`$<-`(`*tmp*`, "b", value = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10,  
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,  ... 

2. FUN(X, Y, ...) 

1. outer(x, y, testf) 

函数本身似乎没有问题,因为testf(1,1)工作

> testf(1,1)
[1] 10

任何建议都将不胜感激!

1 个答案:

答案 0 :(得分:0)

我认为for loop只是生成z轴值的方法