I need to put all the rows that contain a date in a variable as 1 and all the Null or Na's as 0. I need this in a loop.

I have already tried this and it doesn't work

p$n <- ifelse(is.na(n),0,1)

2 Answers

0
Tim Biegeleisen On

The lubridate package features a function is.Date, which can check if a value is a valid R date:

library(lubridate)

p$isdate <- ifelse(is.Date(p$n), 1, 0)

I store the result into a new column isdate, under the assumption that you don't want to clobber your original n column.

0
ianjd On

The reason your code did not work above is that n is probably not an object in your global environment. This should work instead:

p$n <- ifelse(is.na(p$n),0,1)

For example:

p <- data.frame(list(n = c("date",NA,"date",NA,NA, "date")))
p
     n
1 date
2 <NA>
3 date
4 <NA>
5 <NA>
6 date
p$n <-ifelse(is.na(n), 0, 1)
Error in ifelse(is.na(n), 0, 1) : object 'n' not found
#use the '$' operator instead
p$n <-ifelse(is.na(p$n), 0, 1)
p
  n
1 1
2 0
3 1
4 0
5 0
6 1