简体   繁体   English

如果在 R 中,如何与其他多个进行 for?

[英]How to make a for with more than one else if in R?

I want to associate points in these coordinates and associate them with the correspondent number.我想将这些坐标中的点关联起来,并将它们与对应的数字关联起来。 However every time I tried to run it I got this: the condition has length > 1然而,每次我尝试运行它时,我都会得到这个:条件的长度 > 1

for (i in dados) {
    if (dados[dados$latitude>="55.84" & dados$latitude<= "55.95" & dados$longitude>="-3.444" & dados$longitude<="-3.198", ]){
      dados$neighbourhood <- 1
    } else if (dados[dados$latitude>="55.84" & dados$latitude<= "55.95" & dados$longitude>="-3.198" & dados$longitude<="-3.058", ]){
      dados$neighbourhood <- 2
    } else if (dados[dados$latitude>="55.95" & dados$latitude<="56.01" & dados$longitude>="-3.444" & dados$longitude<="-3.198", ]){
      dados$neighbourhood <- 3
    } else if (dados[dados$latitude>="55.95" & dados$latitude<="56.01" & dados$longitude>="-3.189" & dados$longitude<="-3.058", ]){
      dados$neigbourhod <- 4
    }
   }

Your help would be much appreciated thanks in advance.在此先感谢您的帮助。

Here is a vectorized way.这是一种矢量化的方式。 Use the fact that binary numbers are written with 0/1 times powers of two.使用二进制数是用0/1的 2 次幂写入的事实。 And add 1 to have one-based results.并加 1 以获得基于 1 的结果。

i2 <- dados$latitude >= 55.95 & dados$latitude<= 56.01
i1 <- dados$longitude >= -3.198 & dados$longitude <= -3.058
dados$neigbourhod <- 1 + i1 + i2*2

Often, you need to execute some statements only when some condition is met.通常,您需要仅在满足某些条件时才执行某些语句。 You can use following conditional statements in your code to do this.您可以在代码中使用以下条件语句来执行此操作。

if Statement: use it to execute a block of code, if a specified condition is true else Statement: use it to execute a block of code, if the same condition is false else if Statement: use it to specify a new condition to test, if the first condition is false ifelse() Function: use it when to check the condition for every element of a vector if 语句:用它来执行一段代码,如果指定的条件为真 else 语句:用它来执行一段代码,如果相同的条件为假 else if 语句:用它来指定一个新的条件来测试,如果第一个条件为假 ifelse() Function:在检查向量的每个元素的条件时使用它

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

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