I would like to add a column to my table that compares a value with a previous value in an existing column 'farm' (to check if it is the same); and also controls if the value in the current row is "NULL". The objective is to get back in the new column 'switch' the value "new" when the value in the column 'farm' for that row is different from the value in the previous row for the column 'farm'. (exept when the value in farm is "NULL", then I would like to get back "")
See here below the desired output:
farm switch
A
A
NULL
B new
B
B
A new
A
A
B new
B
B
NULL
A new
A
I tried to solve this using the below code:
#To add a new column switch
MyData["switch"] <- NA
#To check if the value is different from the previous row; and if the value is different from NULL
MyData$switch <- ifelse((MyData$farm == lag(MyData$farm))||MyData$farm=="NULL","",MyData$farm)
But when I use this code, then my added column has only empty values? Can somebody please clarify what I am doing wrong and help me with a code that might work?
Aucun commentaire:
Enregistrer un commentaire