Replace integer(0) by NA
Solution 1
Here's a way to (a) replace integer(0)
with NA
and (b) transform the list into a vector.
# 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
Solution 2
Best to do that in your function, I'll call it myFunctionForApply
but that's your current function. Before you return, check the length and if it is 0 return NA
:
myFunctionForApply <- function(x, ...) {
# Do your processing
# Let's say it ends up in variable 'ret':
if (length(ret) == 0)
return(NA)
return(ret)
}
user2498193
Updated on June 30, 2022Comments
-
user2498193 almost 2 years
I have a function that I apply to a column and puts results in another column and it sometimes gives me
integer(0)
as output. So my output column will be something like:45 64 integer(0) 78
How can I detect these
integer(0)
's and replace them byNA
? Is there something likeis.na()
that will detect them ?
Edit: Ok I think I have a reproducible example:
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))
The output from this
sapply
is the source of the problem.> str(sapply(df1$ID,function(x) fetcher(x))) List of 6 $ : num 33 $ : num 11 $ : num(0) $ : num 22 $ : num 55 $ : num 44
I don't want this to be a list - I want a vector, and instead of
num(0)
I wantNA
(note in this toy data it givesnum(0)
- in my real data it gives(integer(0)
).