Вопрос

I am using the following code to extract the number of complete cases from files:

complete <- function(directory, id=1:332) {
    sapply(id, fn, directory)}


fn <- function(id, directory) {
    zero <- sprintf("%03d", id)
    name <- paste(directory,"/",zero,".csv",sep="")
    frame <- read.csv(name)
    ok <- complete.cases(frame)
    return(c("nobs"=sum(ok),"id"=id)) }

Then, e.g.:

complete("specdata",1:12)

This code returns:

     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
nobs  117 1041  243  474  402  228  442  192  275   148   443    96
id      1    2    3    4    5    6    7    8    9    10    11    12

However, I would like it to return a data frame of the type:

enter image description here

I am not sure what I am doing wrong. Thank you!

Это было полезно?

Решение

sapply is returning a matrix here. You can get the shape and type you want with:

as.data.frame(t(complete("specdata",1:12)))

Or put this in the complete function, around the call to sapply. t transposes the matrix rows into columns, and as.data.frame coerces it into such.

Другие советы

Your code is OK. In order to get your desired result use

t(sapply(id, fun, directory))

instead of sapply(id, fun, directory).

Your code should look like this;

complete <- function(directory, id=1:332) {
    t(sapply(id, fn, directory))}
complete <- function(directory, id = 1:332) {

 as.data.frame(t(sapply(id, fn, directory)))




}

fn <- function(id, directory){
if(is.numeric(id)){                                                         
id=id
}else{
id = as.numeric(id)
}
fileName  <- paste(paste(directory,'/',sep=''),paste(id,'.csv',sep=''),sep='')
data  <- read.csv(fileName )
tows <- (complete.cases(data))
rowsNum <- nrow(data[tows,])
return(c("id"=as.numeric(id),"nobs"=rowsNum))

}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top