将整数(0)替换为NA。

8

我有一个应用于某一列并将结果放入另一列的函数,有时会输出integer(0)。因此,我的输出列将是这样的:

45
64
integer(0)
78

如何检测这些integer(0)并用NA替换它们?是否有类似于is.na()的函数可以检测它们?请注意保留HTML标记。
编辑:好的,我想我有一个可重现的例子:
df1 <-data.frame(c("267119002","257051033",NA,"267098003","267099020","267047006"))
names(df1)[1]<-"ID"

df2 <-data.frame(c("257051033","267098003","267119002","267047006","267099020"))
names(df2)[1]<-"ID"
df2$vals <-c(11,22,33,44,55)

fetcher <-function(x){
  y <- df2$vals[which(match(df2$ID,x)==TRUE)]
return(y) 
}

sapply(df1$ID,function(x) fetcher(x))

这个 sapply 的输出是问题的根源。
> str(sapply(df1$ID,function(x) fetcher(x)))
List of 6
$ : num 33
$ : num 11
$ : num(0) 
$ : num 22
$ : num 55
$ : num 44

我不希望这是一个列表 - 我想要一个向量,而不是 num(0),我想要 NA(请注意,在这个玩具数据中它给出了num(0),在我的真实数据中它给出了(integer(0))。


2
data.frame$column[data.frame$column == integer(0) ] <- NA 这段代码能够正常工作吗? - cianius
1
@pepsimax,为什么不把那个作为答案(也许提供一个可行的例子)? - Roman Luštrik
2
数据框中不能包含 integer(0)。请提供一个可重现的示例。 - Sven Hohenstein
1
或者你可以检查 length()==0,参见:https://dev59.com/1Gw15IYBdhLWcg3wtd0g - holzben
1
我也很想知道 integer(0) 是如何出现在你的输出中的。但是为了让你继续前进:要测试一个对象是否为 integer(0),你可以使用 identical(object, integer(0)) - Mark Heckmann
显示剩余8条评论
2个回答

7

以下是一种方法,可以将integer(0)替换为NA,并将列表转换为向量。

# a regular data frame
> dat <- data.frame(x = 1:4)
# add a list including integer(0) as a column
> dat$col <- list(45,
+                 64,
+                 integer(0),
+                 78)
> str(dat)
'data.frame':   4 obs. of  2 variables:
 $ x  : int  1 2 3 4
 $ col:List of 4
  ..$ : num 45
  ..$ : num 64
  ..$ : int 
  ..$ : num 78
# find zero-length values
> idx <- !(sapply(dat$col, length))
# replace these values with NA
> dat$col[idx] <- NA
# transform list to vector
> dat$col <- unlist(dat$col)
# now the data frame contains vector columns only
> str(dat)
'data.frame':   4 obs. of  2 variables:
 $ x  : int  1 2 3 4
 $ col: num  45 64 NA 78

谢谢Sven!通过将其中的部分内容纳入我的函数中,解决了我的问题!非常感谢大家——对于原始问题很抱歉! - user2498193

4
最好在您的函数中进行这个操作,我会把它叫做myFunctionForApply,但那是您当前的函数。在返回前,请检查长度,如果为0,则返回NA:
myFunctionForApply <- function(x, ...) {
    # Do your processing
    # Let's say it ends up in variable 'ret':
    if (length(ret) == 0)
        return(NA)
    return(ret)
}

2
正确。不过代码风格不太符合惯用法:function (x, ...) if (length(ret) == 0) NA else ret - Konrad Rudolph
感谢Ben和Konrad!非常感谢你们的回答! - user2498193
谢谢Calimo,我现在意识到你回答了,而Ben进行了编辑。 - user2498193

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接