在sapply函数中忽略NA [英] Ignore NA's in sapply function
问题描述
我正在使用R并且已经搜索了一个答案,但是当我看到类似的问题时,它并不适用于我的具体问题。
在我的数据集中,我尝试使用 NA
作为占位符,因为我将返回他们有一次我完成了我的部分分析,因此,我希望能够做所有的计算,就好像 NA
不是真的那样。
这是我的问题,用一个示例数据表
ROCA = c (1,3,6,2,1,NA,2,NA,1,NA,4,NA)
ROCA < - data.frame(ROCA = ROCA)#只是因为它是格式我的原始数据
#Now my function
exceedes< - function(L = NULL,R = NULL,na.rm = T)
{
if (is.null(L)| is.null(R)){
print(mycols:invalid L,R。)
return(NULL)
}
test < ;-(平均值(L,na.rm = TRUE)-R * sd(L,na.rm = TRUE))
test1 < - sapply(L,function(x)if((x)> ; test){1} else {0})
return(test1)
}
L = ROCA [,1]
R = 0.5
ROCA $ newcolumn < - exceedes(L,R)
名称(ROCA)[名称(ROCA)==newcolumn] =Exceedes1
出现错误:
if((x)>测试){:缺少值,其中TRUE / FALSE需要
正如你们所知道的那样, sapply f结。关于如何忽略 NA
的任何想法?我会尝试 na.omit
,如果我可以让它插入所有 NA
的权利,但我不知道该怎么做。
这句话很奇怪:
test1< - sapply(L,function(x)if((x)> test){1} else {0})
试试:
test1< ; ifelse(is.na(L),NA,ifelse(L> test,1,0))
I am using R and have searched around for an answer but while I have seen similar questions, it has not worked for my specific problem.
In my data set I am trying to use the NA
's as placeholders because I am going to return to them once I get part of my analysis done so therefore, I would like to be able to do all my calculations as if the NA
's weren't really there.
Here's my issue with an example data table
ROCA = c(1,3,6,2,1,NA,2,NA,1,NA,4,NA)
ROCA <- data.frame (ROCA=ROCA) # converting it just because that is the format of my original data
#Now my function
exceedes <- function (L=NULL, R=NULL, na.rm = T)
{
if (is.null(L) | is.null(R)) {
print ("mycols: invalid L,R.")
return (NULL)
}
test <-(mean(L, na.rm=TRUE)-R*sd(L,na.rm=TRUE))
test1 <- sapply(L,function(x) if((x)> test){1} else {0})
return (test1)
}
L=ROCA[,1]
R=.5
ROCA$newcolumn <- exceedes(L,R)
names(ROCA)[names(ROCA)=="newcolumn"]="Exceedes1"
I am getting the error:
Error in if ((x) > test) { : missing value where TRUE/FALSE needed
As you guys know, it is something wrong with the sapply function. Any ideas on how to ignore those NA
's? I would try na.omit
if I could get it to insert all the NA
's right where they were before, but I am not sure how to do that.
This statement is strange:
test1 <- sapply(L,function(x) if((x)> test){1} else {0})
Try:
test1 <- ifelse(is.na(L), NA, ifelse(L > test, 1, 0))
这篇关于在sapply函数中忽略NA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!