I want to edit a column of a df only if a condition is met by a second column and also keep track of when the condition is false. What is the appropriate way to do this?
I have tried using ifelse() but both the true and false code is always executed. Plus, it seems like the wrong approach since I do not want the ifelse vector output. (Here I only want to evaluate the first row of each ID).
> df <- data.frame(id = rep(c(1,2,3), each = 2), value = rep(c(4,7,-8),
each = 2), new_val = rep(0, each=6))
> neg_val <- vector()
> ifelse(df[!duplicated(df$id), "value"] > 0,
df[!duplicated(df$id), "new_val"] <- df[!duplicated(df$id),"value"],
neg_val <- append(neg_val, df[!duplicated(df$id), "id"]))
[1] 4 7 3
> neg_val
[1] 1 2 3
The output of the ifelse is as I expected, the positive values or the ID of negative values. But the df is updated for all values, not just when value > 0 and neg_val includes all the IDs when I only wanted the IDs for values not > 0.
Aucun commentaire:
Enregistrer un commentaire