mardi 5 octobre 2021

Using if or ifelse

I have a dataframe in which I need to make a single observation in a column different based on the value of a variable in another column. I am new to programming and am having a difficult time finding a concrete example that I can follow. When the Item value is 1615, Epoch should be 261, and at all other levels of Item, Epoch should not change. The dataframe name is myevents. Here is an example of the data:

Item Epoch
1612 260
1613 0
1614 0
1615 0
1616 0
1617 0
1618 262
1619 0

Here is what the output should look like:

Item Epoch
1612 260
1613 0
1614 0
1615 261
1616 0
1617 0
1618 262
1619 0

Here is what I have tried:

myevents$Epoch=ifelse(myevents$Item==1615, myevents$Epoch==261, myevents$Epoch==myevents$Epoch)

myevents$Epoch=ifelse(myevents$Item==1615, myevents$Epoch==261, myevents$Epoch)

myevents$Epoch <- with(myevents, ifelse(myevents$Item==1615, myevents2$Epoch==261, myevents$Epoch==myevents$Epoch))

myevents$Epoch <- with(myevents, if(myevents$Item==1615, myevents$Epoch==261))

None of the above worked, and some actually replace the column with all TRUE or FALSE characters instead. I have made sure all numbers are being treated as numeric, and for good measure I did try wrapping them in single quotes just in case. I've also tried using forms if just if alone but I cannot figure out how to use it in a way that actually runs. Any help is greatly appreciated!

Aucun commentaire:

Enregistrer un commentaire