I would like to replace data in columns rep1 to rep4. The data in these columns match unique ID's in the first column. I want to replace the data in columns rep1-rep4 with data in the value column with the corresponding ID row. So, for the second row "b", I want to replace "a" in the column "rep1" with the corresponding value in row "a", in this case, -400.
ID rep1 rep2 rep3 rep4 value
a -400
b a -300
c a b -200
d a b c -300
e a b c d -400
f -400
g f -400
h -400
i -200
j k l -300
k l -200
l -300
m -300
It seems like using ifelse(!is.na())
might be able to do something here, but I'm not sure how to match the ID data in columns rep1 to rep4 to the corresponding row in the ID column, identifying what data in "value" is supposed to be used in the replacement. Can this be done in the same dataframe, or does it need to be split into two different dataframes to work?
Here is the data using dput()
structure(list(ID = structure(1:13, .Label = c("a", "b", "c",
"d", "e", "f", "g", "h", "i", "j", "k", "l", "m"), class = "factor"),
rep1 = structure(c(1L, 2L, 2L, 2L, 2L, 1L, 3L, 1L, 1L, 4L,
5L, 1L, 1L), .Label = c("", "a", "f", "k", "l"), class = "factor"),
rep2 = structure(c(1L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 3L,
1L, 1L, 1L), .Label = c("", "b", "l"), class = "factor"),
rep3 = structure(c(1L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L), .Label = c("", "c"), class = "factor"), rep4 = structure(c(1L,
1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("",
"d"), class = "factor"), value = c(-400L, -300L, -200L, -300L,
-400L, -400L, -400L, -400L, -200L, -300L, -200L, -300L, -300L
)), class = "data.frame", row.names = c(NA, -13L))