简体   繁体   English

R中的for循环的行为异常

[英]for loop in R behaves in unexpected way

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 在data.frame(id = id,nobs = temp)中显示带有调试错误的Traceback重新运行:参数暗示不同的行数:5、12

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. 您得到不匹配的行长的原因是因为temp[i]将输出分配给temp中的第i个地标。 So when you try c(2, 4, 8, 10, 12) . 因此,当您尝试c(2, 4, 8, 10, 12) You are expecting to get a vector of length five for temp . 您期望得到temp的长度为5的向量。 but you get a vector of length 12. Because temp[12] an element of the output. 但是您得到的矢量长度为12。因为temp[12]是输出的元素。 So temp is stretched out to that length. 因此, temp一直延伸到该长度。 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. 当我给x的第五个元素赋值时,R扩展了向量而没有要求我执行任务。

complete("specdata", 3) returned 3 answers because temp initially had one value, 0 . complete(“ specdata”,3)返回3个答案,因为temp最初只有一个值0 You preassigned it at the beginning. 您在开始时已将其预先分配。 Then the for loop assigned 243 to temp[3] as you instructed it to. 然后,for循环按照您的指示将243分配给temp[3] So R filled in an NA value for the second value, and you were left with three. 因此,R为第二个值填充了一个NA值,然后剩下三个。

  id nobs
1  3    0
2  3   NA
3  3  243

Change this lines in your code function to: 在代码函数中将此行更改为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM