2014-01-19 124 views
4

我有一个函数可以应用于列,并将结果放在另一列中,它有时候会给我integer(0)作为输出。所以,我的输出列将是这样的:用NA替换整数(0)

45 
64 
integer(0) 
78 

我如何检测这些integer(0)的和NA取代他们?有没有像is.na()那样会检测到它们?


编辑:好吧,我想我有一个重复的例子:

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

would data.frame $ column [data.frame $ column == integer(0)] < - NA work? – cianius

+1

@pepsimax你为什么不把它作为答案(也许提供一个工作的例子)? –

+2

数据帧不能包含“整数(0)”。请提供一个可重复的例子。 –

回答

5

这里有一个办法(一)取代integer(0)NA和(b)转换列表到载体中。

# 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 
+0

谢谢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) 
} 
+1

正确。尽管非常非惯用的代码:'function(x,...)if(length(ret)== 0)否则ret' –

+0

感谢Ben和Konrad!欣赏你的答案! – user2498193

+0

谢谢Calimo我意识到现在你回答了,Ben编辑 – user2498193