Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace integer(0) by NA

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 by NA? Is there something like is.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 want NA (note in this toy data it gives num(0) - in my real data it gives (integer(0)).

like image 971
user2498193 Avatar asked Jan 19 '14 14:01

user2498193


People also ask

How do I replace 0 with Na?

Using R replace() function to update 0 with NA R has a built-in function called replace() that replaces values in a vector with another value, for example, zeros with NAs.

How do I replace all values with NA in R?

Use replace_with_na_all() when you want to replace ALL values that meet a condition across an entire dataset.

How do you catch an integer 0 in R?

Sometimes when you use the which() function in R, you may end up with integer(0) as a result, which indicates that none of the elements in a vector evaluated to TRUE. Since none of the elements in the vector are equal to 10, the result is an integer of length 0, written as integer(0) in R.


1 Answers

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
like image 179
Sven Hohenstein Avatar answered Oct 06 '22 00:10

Sven Hohenstein