2021年3月9日星期二

Updating values in some rows using values in other rows, based on some conditions on other columns

I have a huge dataset in which I would like to update the values in some of the rows (i.e, that have scenario=="D") with the value in another cell in the same column (i.e., column outcome) from another row (i.e, that has scenario=="C"), conditional on having the same values for other columns (i.e., year and country)

df <- data.frame(year=c("2000", "2000", "2001", "2001"),                   country=c("A", "A", "B", "B"),                   scenario=c("C", "D", "C", "D"),                   outcome=c("1", "2", "3", "4"))  

I would like to generate this:

df2 <- data.frame(year=c("2000", "2000", "2001", "2001"),                   country=c("A", "A", "B", "B"),                   scenario=c("C", "D", "C", "D"),                   outcome=c("1", "1", "3", "3"))  

I would appreciate any help.

https://stackoverflow.com/questions/66557331/updating-values-in-some-rows-using-values-in-other-rows-based-on-some-condition March 10, 2021 at 09:58AM

没有评论:

发表评论