Reputation: 1
I am trying to update the Status column in my data set when the Diff value is < 0, so therefore when the Diff value is a -neg number I want to make the Status column = 1 to represent a change. below is sample code of my data set which is all numeric:
df <- as.data.frame(list(diff=c("4","0","0","0","0","0","0","0","0","0",
"0","-30","0","0","0","0","0","0","0","0",
"14","0","0","0","0","0","0","-55","0","0",
"0","0","0","0","0","0","0","0","0","0",
"0","0","0","-40","0","0","0","0","0","0",
"0","0","0","0","0","0","0","0","0","0",
"0","-30","0","0","0","0","0","0","0","0",
"0","0","0","0","0"),
status=c("0","0","0","0","0","0","0","0","0","0",
"0","0","0","0","0","0","0","0","0","0",
"0","0","0","0","0","0","0","0","0","0",
"0","0","0","0","0","0","0","0","0","0",
"0","0","0","0","0","0","0","0","0","0",
"0","0","0","0","0","0","0","0","0","0",
"0","0","0","0","0","0","0","0","0","0",
"0","0","0","0","0")))
Upvotes: 0
Views: 90
Reputation: 263441
You've created a difficult problem by giving a set of character values to the data.frame function. By default that will create factor variables unless you set stringsAsFactors=FALSE
. Two thing are consequential: the comparisons to 0 will fail and assignment to a value that doesn't exist in the df$status column will likewise fail.
df <- data.frame(diff=c("4","0","0","0","0","0","0","0","0","0",
"0","-30","0","0","0","0","0","0","0","0",
"14","0","0","0","0","0","0","-55","0","0",
"0","0","0","0","0","0","0","0","0","0",
"0","0","0","-40","0","0","0","0","0","0",
"0","0","0","0","0","0","0","0","0","0",
"0","-30","0","0","0","0","0","0","0","0",
"0","0","0","0","0"),
status=c("0","0","0","0","0","0","0","0","0","0",
"0","0","0","0","0","0","0","0","0","0",
"0","0","0","0","0","0","0","0","0","0",
"0","0","0","0","0","0","0","0","0","0",
"0","0","0","0","0","0","0","0","0","0",
"0","0","0","0","0","0","0","0","0","0",
"0","0","0","0","0","0","0","0","0","0",
"0","0","0","0","0"), stringsAsFactors=FALSE)
Once those issues are put aside you can get success with a logical indexed assignment like:
df$status[as.numeric(df$diff) < 0 ] <- 1
Upvotes: 1
Reputation: 387
library(dplyr)
df <- df %>%
mutate(status = ifelse(diff < 0, 1, 0))
Upvotes: 0