[英]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: 基本上,我想使用以下条件在末尾添加新列:
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:
rowSums(matrix(NA, 3, 3), na.rm = T)
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.