返回

在tibble中打印列和行的R函数-我做错了什么?

发布时间:2022-05-28 13:45:58 234

我创建了一个函数来打印TIBLE中指定的列块和行块,它基本上工作得很好。有一件小事我想不出来。当我有一个较小的数据集并且想要打印所有列(在指定的行范围内)时,如果我指定列数作为参数,则不会打印任何内容。但是,如果我少指定一列,它会打印,但会在控制台中拆分为两组行。在这种情况下,我希望能够查看一行上的所有数据。

我的功能和一些测试数据如下:

# Need to specify:
# 1.Dataframe name
# 2.Number of cols to print in a block
# 3.Start row
# 4.End row
  print_cols <- function(df, ncols, rowstart, rowend) {
    numcols <- length(df)
    i <- 1
    while (i + (ncols-1) < numcols) {
      cat("\n")
      print(paste0("Columns ", i, " to ", (i + (ncols-1)), ": Rows ", rowstart, " to ", rowend))
      print(df[rowstart:rowend, i:(i + (ncols-1))], n = Inf)
      i <- i + ncols
      if (i + (ncols-1) >= numcols) {
        cat("\n")
        print(paste0("Columns ", i, " to ", numcols, ": Rows ", rowstart, " to ", rowend))
        print(df[rowstart:rowend, i:numcols], n = Inf)
      }
    }
  }

# Simulate data and test function
# Print blocks of cols (when many variables)  
dat <- rep(rnorm(50, 50, 20), 100)
dat <- as_tibble(matrix(data = dat, nrow = 50, ncol = 100, byrow = F))
print_cols(dat, 20, 20, 40) # works fine

# Print all columns (when only a few variables)
dat2 <- rep(rnorm(50, 50, 20), 10)
dat2 <- as_tibble(matrix(data = dat2, nrow = 50, ncol = 10, byrow = F))
print_cols(dat2, 10, 20, 40) # prints nothing - WHY??
print_cols(dat2, 9, 20, 40) # need to specify one column less in order to print``` 
特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报
评论区(1)
按点赞数排序
用户头像
相关帖子