R中If语句的逻辑“Except”运算符

时间:2013-06-03 23:09:19

标签: r conditional-statements logical-operators

仅供参考,我是使用R的新手,所以我的代码可能非常笨重。我已完成了这项功课,但未能找到R的“Except”逻辑运算符,并且在我的代码中确实需要类似的东西。我的输入数据是.csv,包含整数和空值,包含12列和1440行。

oneDayData <- read.csv("data.csv") # Loading data
oneDayMatrix <- data.matrix(oneDayData, rownames.force = NA) #turning data frame into     a matrix


rowBefore <- data.frame(oneDayData[i-1,10], stringsAsFactors=FALSE) # Creating a variable to be used in the if statement, represents cell before the cell in the loop

ctr <- 0 # creating a counter and zeroing it


for (i in 1:nrow(oneDayMatrix)) {
  if ((oneDayMatrix[i,10] == -180) & (oneDayMatrix[i,4] == 0)) { # Makes sure that there is missing data matched with a zero in activityIn
    impute1 <- replace(oneDayMatrix[ ,10], oneDayMatrix[i,10], rowBefore)
    ctr <- (ctr + 1) # Populating the counter with how many rows get changed
  }
  else{
    print("No data fit this criteria.")
  }
}
print(paste(ctr, "rows have been changed.")) # Printing the counter and number of rows that got changed enter code here

我想在我的if语句或等效语句中添加某种EXCEPT条件,例如:使用前两个条件(参见代码中的语句)除了oneDayMatrix [i-1,4]&gt;我真的很感激任何帮助,并提前感谢你!

1 个答案:

答案 0 :(得分:0)

“除外”相当于“如果不是”。 R中的“not”运算符为!。因此,要添加oneDayMatrix[i-1, 4] > 0例外,您只需修改if语句,如下所示:

if ((oneDayMatrix[i,  10] == -180) &
    (oneDayMatrix[i,   4] ==  0)   &
   !(oneDayMatrix[i-1, 4]  >  0)) { ... }

或等效地:

if ((oneDayMatrix[i,  10] == -180) &
    (oneDayMatrix[i,   4] ==  0)   &
    (oneDayMatrix[i-1, 4] <=  0)) { ... }

除了需要对您的代码进行的一些修复之外,还有其他功能:

  1. 正如我所指出的那样,rowBefore未正确定义:就i而言尚未定义。在for循环中,只需将rowBefore替换为oneDayMatrix[i-1, 10]
  2. 即可
  3. 正如@noah指出的那样,你需要在第二个索引处开始你的循环:for (i in 2:nrow(oneDayMatrix))