R - 按名称将数据帧列传递给R函数

时间:2016-07-08 14:21:33

标签: r

我有一个简单的函数,我想使用响应变量" y"对数据框进行一些统计。

#include <iostream>
#include "stlvecs.hpp"
#include "nestedLoop.hpp"

int main(){
    nestedLoop::nestedLoop looper;
    std::vector<int> maxes = {2, 3, 2, 2};
    looper.reset(4,maxes);
    int i = 0;
    while(looper.next()){
        std::cout << "Indices: " << looper.idxes << ", Last nest incremented: " << looper.nestLevel << std::endl;
        if(i == 5){
            std::cout << "...Jump Second Nest (index 1)..." << std::endl;
            looper.jumpNest(1);
        }
        i++;
    }
}

/* Expected output
Indices: 4  0 0 0 0 , Last nest incremented: 0
Indices: 4  0 0 0 1 , Last nest incremented: 3
Indices: 4  0 0 1 0 , Last nest incremented: 2
Indices: 4  0 0 1 1 , Last nest incremented: 3
Indices: 4  0 1 0 0 , Last nest incremented: 1
Indices: 4  0 1 0 1 , Last nest incremented: 3
...Jump Second Nest (index 1)...
Indices: 4  0 2 0 0 , Last nest incremented: 1
Indices: 4  0 2 0 1 , Last nest incremented: 3
Indices: 4  0 2 1 0 , Last nest incremented: 2
Indices: 4  0 2 1 1 , Last nest incremented: 3
Indices: 4  1 0 0 0 , Last nest incremented: 0
Indices: 4  1 0 0 1 , Last nest incremented: 3
Indices: 4  1 0 1 0 , Last nest incremented: 2
Indices: 4  1 0 1 1 , Last nest incremented: 3
Indices: 4  1 1 0 0 , Last nest incremented: 1
Indices: 4  1 1 0 1 , Last nest incremented: 3
Indices: 4  1 1 1 0 , Last nest incremented: 2
Indices: 4  1 1 1 1 , Last nest incremented: 3
Indices: 4  1 2 0 0 , Last nest incremented: 1
Indices: 4  1 2 0 1 , Last nest incremented: 3
Indices: 4  1 2 1 0 , Last nest incremented: 2
Indices: 4  1 2 1 1 , Last nest incremented: 3
*/

如何正确地将y传递给以下部分?:

validation <- function(data,y){

 library(ISLR)
 library(leaps)

 data <- na.omit(data)
 coll <- ncol(data)-1

  attach(data)

 train <- sample(c(TRUE,FALSE),nrow(data),rep=TRUE)
 test <- (!train)

 regfit.best <- regsubsets(y ~.,data= data[train,],nvmax = coll)
 test.mat <- model.matrix(y ~.,data=data[test,])

 val.errors <- rep(NA,coll)

 for(i in 1:coll){

  coefi <- coef(regfit.best,id=i)
  pred <- test.mat[,names(coefi)]%*%coefi
  val.errors[i]= mean((data[[y]][test]-pred)^2)
}

return(val.errors)

}

例如,呼叫验证(Hitters,&#34; Salary&#34;)应该产生

 regfit.best <- regsubsets(y ~.,data= data[train,],nvmax = coll)
 test.mat <- model.matrix(y ~.,data=data[test,])

 val.errors[i]= mean((data[[y]][test]-pred)^2)

0 个答案:

没有答案