首页 > 解决方案 > 获取给定输入值的数据框范围(即 1 返回 df[1:10,])

问题描述

我有一个数据帧 df,我想在 R 中创建一个函数,它返回给定输入数字的数据帧的 10 个条目的范围。那是:

    If input number is equal to 1, the function returns df[1:10,]

    If input number is equal to 2, the function returns df[11:20,]

    If input number is equal to 3, the function returns df[21:30,]

    ...

就像它们是页面一样:第 1 页显示十个条目,第 2 页显示接下来的十个条目,依此类推。

笔记:

  1. 如果没有更多的“十个条目”要返回,该函数应该返回数据框中剩下的所有内容

  2. 数据框的长度不固定(即函数要求使用 df 并返回“页面”)。

它看起来很容易实现,但我不知道如何以正确和快速的方式做到这一点。

编辑

我的意思是返回行而不是列,抱歉。刚刚编辑。但是@Freakazoid 解决方案或多或少起到了作用,只需将 ncol 更改为 nrow (请参阅下面的解决方案)

标签: rdataframe

解决方案


以下函数可以解决问题:

df <- data.frame(matrix(rnorm(1020), nrow=54, ncol=3))

batch_df <- function(df, batch_part) {
  nbr_row <- nrow(df)
  batch_size <- 10
  nbr_of_batchs <- as.integer(nbr_row/batch_size)
  last_batch_size <- (nbr_row - nbr_of_batchs*batch_size) 

  batch_indizes <- c(rep(1:nbr_of_batchs, each=batch_size), 
                     rep(nbr_of_batchs+1, last_batch_size))

  if(all(batch_part %in% batch_indizes)) {
    row_index <- which(batch_indizes %in% c(batch_part))
    ret_df <- df[ row_index,]
  } else {
    ret_df <- data.frame()
  }
  return(ret_df)
}

batch_df(df, 3)

该函数首先定义行的索引。使用这些索引,该函数将搜索您要选择的 batch_part。该函数不仅可以取单个数字;它可以是一个给定的向量,您可以在其中一次选择多个批次零件。

输出:

       X1          X2         X3
21  0.7168950  0.88057886  0.1659177
22 -1.0560819 -0.53230247 -0.4204708
23  0.4835649 -1.43453719  0.1563253
24  0.1266011  1.22149179 -0.7924120
25  0.3982262 -0.59821992 -1.1645105
26 -0.4809448  0.42533877  0.2359328
27 -0.1530060 -0.23762552  0.9832919
28  0.8808083 -0.06004995 -1.0810818
29 -0.2924377 -1.23812802 -0.9057353
30 -0.2420152 -0.52037258  0.7406486

推荐阅读