将整数序列添加到具有大约 500 行的数据框中

Adding a sequence of integers to a data frame having approx 500 rows

我有一个包含 506 行的数据框。我正在尝试使用线性回归模型实现 k 折交叉验证。这是我的 CSV.

的 link

我正在使用留一法模型准备训练和测试数据框。 我收到以下输入:

df - data frame with 506 records
k  - fold cross-validation (example: 10)

这就是我准备测试和训练数据帧所做的工作:

df <- c(1:506) # This is just for representation purposes
df <- cbind(idx, df)
for(ii in 1:k) {
  train <- subset.data.frame(df, df[,1] == ii)
  test <- subset.data.frame(df, df[,1] != ii)
  # Further processing with train and test datasets
}

这给了我一个包含 5060 个条目的 df。

  idx  df
1   1   1
2   1   2
3   1   3
4   1   4
5   1   5
6   1   6
7   1   7
8   1   8
9   1   9
10  1  10
11  1  11
...
506 1 506
507 2   1
508 2   2

然而,我想要的是将数据帧分成k等份:

   idx  df
1    1   1
2    1   2
3    1   3
4    1   4
5    1   5
6    1   6
...
48   1  48
49   1  49
50   1  50
51   1  51
52   2  52
53   2  53
54   2  54
...
504 10 504
505 10 505
506 10 506

我是 R 的新手。所以如果可能,请使用基础包,以便我了解我做错了什么?

如果我没理解错的话,问题出在你的idx栏上。以下是如何使用不能完全适合存储桶的数据创建序列。您有 506 个观测值要放入 10 个桶中。一些桶将包含比其他桶更多的数据。

df <- 1:506
idx <-ceiling(seq_along(df)/(length(df)/10))
df <- cbind(idx, df)

在你的循环中,我使用 subset 因为 df 不是 data.frame。不管怎样,R 通常会弄清楚它处理的是什么类型的数据。

k <-10
for(ii in 1:k) {
  train <- subset(df, df[,1] == ii)
  test <-  subset(df, df[,1] != ii)
  # Further processing with train and test datasets
}

更新

csv 数据加载到 data.frame:

df <-read.csv("C:/temp/house_with_missing.csv",stringsAsFactors = FALSE)                   
idx <-ceiling(seq_along(1:nrow(df))/(nrow(df)/10))                
df <- cbind(idx, df)