2014-01-19 173 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