for loop in R behaves in unexpected way

时间:2015-06-30 13:40:09

标签: r loops for-loop

I'm writing this function and my loop is behaving in a different way. can you explain why it does this and how to correct?

    complete <- function(directory, id = 1:332)  {
    specd <- list.files("specdata", full.names = TRUE)
    temp<- vector(mode = "numeric", (length = length(id)))
    for (i in id)   {
    temp[i] <- nrow(na.omit(read.csv(specd[i])))
    }
    return(data.frame(id = id, nobs = temp))
    }

code:

complete("specdata", 1)OBSERVATION – id = 1; yields 1 answer
  id nobs
1  1  117
complete("specdata", 3) OBSERVATION – id = 3; yields 3 answers
  id nobs
1  3    0
2  3   NA
3  3  243
complete("specdata", 30:25) OBSERVATION – id = 30; yields 30 answers
complete("specdata", c(2, 4, 8, 10, 12))

Show Traceback Rerun with Debug Error in data.frame(id = id, nobs = temp) : arguments imply differing number of rows: 5, 12

2 个答案:

答案 0 :(得分:0)

Try this:

complete <- function(directory, id = 1:332)  {
specd <- list.files("specdata", full.names = TRUE)
temp<- c()
for (i in id)   {
temp <- c(temp,nrow(na.omit(read.csv(specd[i]))))
}
return(data.frame(id = id, nobs = temp))
}

The reason you are getting mismatched row lengths is because temp[i] assigns the output to the ith placemark in temp. So when you try c(2, 4, 8, 10, 12). You are expecting to get a vector of length five for temp. but you get a vector of length 12. Because temp[12] an element of the output. So temp is stretched out to that length. Example:

x <- 1
x
[1] 1
x[5] <- 2
x
[1]  1 NA NA NA  2

When I assigned a value to the fifth element of x, R expanded the vector without asking me to do the task.

complete("specdata", 3) returned 3 answers because temp initially had one value, 0. You preassigned it at the beginning. Then the for loop assigned 243 to temp[3] as you instructed it to. So R filled in an NA value for the second value, and you were left with three.

  id nobs
1  3    0
2  3   NA
3  3  243

答案 1 :(得分:0)

将代码函数中的这一行更改为:

temp<- vector()
for (i in 1:length(id))