replace columns with "0" and "1"

this is my data frame: enter image description here

i want to replace columns Price with number with "1" and "0" for NA, and i want my output like this:

Time                      Price
2018-03-05 09:00:00         1
2018-03-05 09:00:00         1
2018-03-05 09:00:00         1
2018-03-05 09:00:00         1
.                           .
.                           .
2018-03-05 09:02:00         0

Upvotes: 0

Views: 386

Answers (3)

uber
uber

Reputation: 114

You can use ifelse()

df$Price <- ifelse(!is.na(df$Price), 1, 0)

Upvotes: 0

ThomasIsCoding
ThomasIsCoding

Reputation: 101327

  • You can use ifelse from base R for the replacement task, i.e.,
df <- within(df, Price <- ifelse(is.na(Price),0,1))
  • or just 1 - is.na() to generate sequence with 1 and 0
df <- within(df, Price <- 1 - is.na(Price))

Upvotes: 0

Sotos
Sotos

Reputation: 51582

You can use is.na() and convert its logical output to a numeric via as.integer, i.e.

df$Price <- as.integer(!is.na(df$Price)) 

Upvotes: 3

Related Questions