简体   繁体   English

循环“ ifelse”,包括NA

[英]Loop “ifelse” including NA

I want to run a loop using ifelse() and including NA in R. Here is a example of my dataset named DATA : 我想使用ifelse()并在R中包含NA来运行循环。这是我的数据集DATA的示例:

[,1]   [,2]    [,3]    [,4]
ID1     NA      NA      NA
ID2     0       0       0
ID3     1       1       1
ID4     0       0       1
ID5     1       1       0
ID6     0       NA      1
ID7     NA      0       0
ID8     NA      1       1

Basically, I want to add a new column at the end using these criteria: 基本上,我想使用以下条件在末尾添加新列:

  • If there is at least one "1" in column 2, 3 or 4 => 1 如果第2、3或4列中至少有一个“ 1” => 1
  • If there is NO "1" in column 2, 3 or 4, but at least one "0" => 0 如果第2、3或4列中没有“ 1”,但至少有一个“ 0” => 0
  • If there is only "NA" in column 2, 3 or 4 => NOTHING 如果第2、3或4列中只有“ NA” =>否

I thought to use something like that, but it doesn't work. 我曾想使用类似的方法,但这是行不通的。 It returns: 它返回:

"NA" if there is no "1", but at least one "0", instead of
"NOTHING"

Example for line 6: 第6行的示例:

*ifelse(any((DATA[6,c(2:4)])==1), "1", ifelse(any((DATA[6,c(2:4)])==0), "0",
"NOTHING"))*

I don't really want to return "NOTHING" . 我真的不想返回“ NOTHING” In reality I want "NA" , but to verify if a "NA" was the result of something that doesn't work, I used "NOTHING". 实际上,我想要“ NA” ,但是为了验证“ NA”是否是某些无效的结果,我使用了“ NOTHING”。 I also want to loop the whole thing for each line in my data set, but I'm not very good at it either. 我也想遍历数据集中的每一行,但是我也不是很擅长。

rowSums.na <-
    function(x, na.rm = T){

        suma <- rowSums(x, na.rm = na.rm)
        ind  <- apply(x, 1, function(el){ all(is.na(el)) })

        suma[ind] <- NA

        return(suma)
}

df1$newCol<- +(rowSums.na(df1[,2:4]) > 0)

#> df1$newCol
#[1] NA  0  1  1  1  1  0  1

  • df1 is your data. df1是您的数据。
  • normal rowSums / sum returns 0 when all values are NA . 当所有值均为NA时,常规rowSums / sum返回0。 A great mistake IMO. 海事组织这是一个很大的错误。 Eval: EVAL:

    1. rowSums(matrix(NA, 3, 3), na.rm = T)
    2. rowSums.na(matrix(NA, 3, 3))
  • +( ... ) will convert the boolean into a numeric type. +( ... )将布尔值转换为数字类型。 run +( c(TRUE, FALSE, TRUE) ) in R console. 在R控制台中运行+( c(TRUE, FALSE, TRUE) )

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

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