I am trying to create a column ID
based on logical statements for values of other columns. For example, in the following dataframe
test <- st
You might also try an elseif.
x <- 1
if (x ==1){
print('same')
} else if (x > 1){
print('bigger')
} else {
print('smaller')
}
So, I hear this works:
Data$X1<-as.character(Data$X1)
Data$GEOID<-as.character(Data$BLKIDFP00)
Data<-within(Data,X1<-ifelse(is.na(Data$X1),GEOID,Data$X2))
But I admit I have only intermittent luck with it.
@AnandaMahto has addressed why you're getting these results and provided the clearest way to get what you want. But another option would be to use identical
instead of ==
.
test$ID <- ifelse(is.na(test$time) | sapply(as.character(test$type), identical, "A"), NA, "1")
Or use isTRUE
:
test$ID <- ifelse(is.na(test$time) | Vectorize(isTRUE)(test$type == "A"), NA, "1")
You can't really compare NA
with another value, so using ==
would not work. Consider the following:
NA == NA
# [1] NA
You can just change your comparison from ==
to %in%
:
ifelse(is.na(test$time) | test$type %in% "A", NA, "1")
# [1] NA "1" NA "1"
Regarding your other question,
I could get this to work with my existing code if I could somehow change the result of
is.na(test$type)
to returnFALSE
instead ofTRUE
, but I'm not sure how to do that.
just use !
to negate the results:
!is.na(test$time)
# [1] TRUE TRUE FALSE TRUE
It sounds like you want the ifelse statement to interpret NA values as FALSE instead of NA in the comparison. I use the following functions to handle this situation so I don't have to continuously handle the NA situation:
falseifNA <- function(x){
ifelse(is.na(x), FALSE, x)
}
ifelse2 <- function(x, a, b){
ifelse(falseifNA(x), a, b)
}
You could also combine these functions into one to be more efficient. So to return the result you want, you could use:
test$ID <- ifelse2(is.na(test$time) | test$type == "A", NA, "1")