首页 文章

R逐列子集化数据

提问于
浏览
-2

对于赋值,我编写了一个以“id”作为参数的函数,其中我创建了一个空数据框,然后在for循环中读取一系列CSV文件中的完整案例数(无NA) . 这给了我一个带有两列(id,#完整例)的数据框“dat”,我已经验证了这一点 . 现在我遇到基于id参数的子集化问题 . 我应该能够按列1进行子集,这相当于id:

dat[which(dat[, 1] %in% id),]

但是当我运行这个函数时,没有返回任何内容(没有输出,没有错误) . 在对这个网站和其他网站进行一些搜索之后,我尝试在创建数据框时命名列,以便在子集中调用列:

dat <- data.frame("monitor"=integer(), "nobs"=integer())
dat_subset <- dat[which(dat[, "monitor"] %in% id),]

但是这会返回“未定义的列选择” . 所以我尝试用另一种方式指定我的数据框:

dat <- data.frame(ncol=2)
colnames(dat) <- c("ID", "nobs")

但是这给出了错误'names'属性[2]必须与vector [1]的长度相同 . 1矢量的长度是多少?我没有要求2列数据框吗?

任何人都可以帮我调试这些选项吗?非常感谢!

根据反馈进行编辑:我通过数据框正确初始化(感谢评论) . dat < - data.frame("ID" = integer(0),"nobs" = integer(0)) Str(dat) 表示我已正确完成此操作'data.frame':0 obs . 2个变量:$ ID:int $ nobs:int所以看来我的问题在于后面的for循环,因为在循环显示列名已被删除后使用 str(dat)

for (i in 1:332) {
        nobs <- sum(complete.cases(read.csv(files_list[i])))
        rowvector <- c(i,nobs)
        dat <- rbind(dat, rowvector)
  }
'data.frame':   332 obs. of  2 variables:
 $ X1L  : int  1 2 3 4 5 6 7 8 9 10 ...
 $ X117L: int  117 1041 243 474 402 228 442 192 275 148 ...

为数据框添加行时,为什么名称不会粘住? ?rbind 表示"column names are taken from the first argument with appropriate names" .

1 回答

  • 0

    我相信这是你正在寻找的,利用 subset 功能 .

    fun <- function(want) {
      # Here's a random example
      # dat <- data.frame(id = rep(1:3, each = 3),
      #                   n_complete = as.integer(runif(9, max = 100)))
      # > str(dat)
      # 'data.frame':   9 obs. of  2 variables:
      #   $ id        : int  1 1 1 2 2 2 3 3 3
      #   $ n_complete: int  3 80 5 84 67 83 48 49 52
    
      # Or using the file reading code from the question edit
      # dat <- data.frame(id = integer(), n_complete = integer())
      # for (i in 1:332) {
      #   nobs <- sum(complete.cases(read.csv(files_list[i])))
      #   dat <- rbind(dat, data.frame(id = i, n_complete = nobs))
      # }
    
      # Better yet, preallocate dat before filling
      dat <- data.frame(id = 1:332, n_complete = 0)
      for (i in dat$id) {
        nobs <- sum(complete.cases(read.csv(files_list[i])))
        dat$n_complete[i] <- nobs
      }
    
      # Subset by requesting specific id values
      return(subset(dat, id %in% want))
    }
    
    # Ask for ids 1 and 2
    fun(c(1, 2))
    # > str(fun(c(1, 2)))
    # 'data.frame': 6 obs. of  2 variables:
    #   $ id        : int  1 1 1 2 2 2
    #   $ n_complete: int  3 80 5 84 67 83
    

相关问题