如何在R中将值从循环存储到数据帧?

时间:2019-01-16 19:06:50

标签: r loops dataframe

我不熟悉R和编程,我想将循环中的值存储到R中的数据帧。我希望将x <- c(1,2,3.5,4,5,6,7,8,9,10,11,12,13,14,15, + 16,17,18,19,20) kercValues值存储到数据中波纹管代码中的帧。我无法实现这一点,数据框仅保存了最后一个值,而不是所有值。

能帮我吗?

accuracyValues

2 个答案:

答案 0 :(得分:1)

从基本代码开始,设置输出数据帧的结构。然后,遍历并在每次迭代中填写精度值。此方法还会“拉平”嵌套循环,并摆脱与内置c函数冲突的c()变量。

kerna <- c("rbfdot","polydot","vanilladot","tanhdot","laplacedot",
           "besseldot","anovadot","splinedot")

# Create dataframe to store output data
df <- data.frame(kerna = rep(kerna, each = 100), 
                 cValues = rep(1:100, times = length(kerna)),
                 accuracyValues = NA,
                 stringsAsFactors = F)

# Define a for loop to calculate accuracy for different values of C and kernel
for (i in 1:nrow(df)){
  ker <- df$kerna[i]
  j <- df$cValues[i]
  model <- ksvm(V11~V1+V2+V3+V4+V5+V6+V7+V8+V9+V10,
                data = credit_card_data,
                type ="C-svc",
                kernel = ker,
                C=j,
                scaled =TRUE)
  pred <- predict(model,credit_card_data[,1:10])
  accuracy <- sum(pred== credit_card_data$V11)/nrow(credit_card_data)

  # Insert accuracy into df$accuracyValues
  df$accuracyValues[i] <- accuracy;
}

答案 1 :(得分:0)

考虑Map,以根据从{{1}生成的 ker cValues 1:100)的每对构建数据帧列表}和row将所有元素绑定在一起。

expand.grid