【问题标题】:Complete function in R [duplicate]R中的完整功能[重复]
【发布时间】:2017-02-20 14:16:18
【问题描述】:

我正在做以下工作。该功能仅在传递一个 ID 时起作用。但是,如果传递了多个 ID(例如 c(2,4,6) 或 2:6),则输出不正确。

编写一个函数,读取一个满是文件的目录,并报告每个数据文件中完全观察到的病例数。该函数应返回一个数据框,其中第一列是文件名,第二列是完整案例的数量。这是我的代码,虽然它在仅传递一个 ID 时有效,但在传递更多 ID 或一系列 ID 时似乎无法获得正确的输出。这是一个原型:

complete <- function(directory, id = 1:332) {
    ## 'directory' is a character of length 1 
    ## indicating the location of the CSV file

    ## 'id' is an integer vector 
    ## indicating the monitor ID numbers to be used

    ## Return a data frame of the form:
    ## id nobs
    ## 1 117
    ## 2 1041
    ## ...
    ## where 'id' is the monitor ID number and 
    ## 'nobs' is the number of complete cases
}

这是我的代码:

complete <- function(directory, id = 1:332) {
    #lists the files in the directory
    files_full <- list.files(directory, full.names = TRUE) 

    #empty data frame were we will store the read from the loop
    dat <- data.frame()  

    nobs = numeric()
    for (i in id) {
            ## binds all the rows of the of the files with "specified" ID                
            dat <- rbind(dat, read.csv(files_full[i])) 

            nobs <- sum(complete.cases(dat))
    }
    returnVal <- data.frame(id, nobs)
    returnVal
}

这些是输出:

complete("specdata", 1)

  id nobs
1  1  117

complete("specdata", c(2, 4, 8, 10, 12))

  id nobs
1  2 1951
2  4 1951
3  8 1951
4 10 1951
5 12 1951

谁能告诉我我做错了什么?

【问题讨论】:

    标签: r function


    【解决方案1】:

    您正在从堆叠的数据框中计算 nobs。 1951 是整个 ID 的完整案例的总和。您需要分别计算和存储每个 id 的完整案例数

    nobs = rep(0, length(id))
    k <- 1
    for (i in id) {
      dat <- read.csv(files_full[i])
      nobs[k] <- sum(complete.cases(dat))
      k <- k + 1
    }
    returnVal <- data.frame(id, nobs)
    

    【讨论】:

    • 它确实有效,我明白你的意思。感谢您的帮助!
    猜你喜欢
    • 2016-03-15
    • 2017-11-07
    • 1970-01-01
    • 2018-09-03
    • 2016-11-27
    • 1970-01-01
    • 2014-12-14
    • 2011-05-05
    • 1970-01-01
    相关资源
    最近更新 更多