-1

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)
zack
  • 5,205
  • 1
  • 19
  • 25
  • `p$n <- ifelse(is.na(p$n),0,1)` should work - when you refer to `n` in the `is.na` call, r doesn't know you want the column of `p` – zack May 13 '19 at 14:39

2 Answers2

0

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.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

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
Dij
  • 1,318
  • 1
  • 7
  • 13