A dataframe has columns code1
, code2
, code3
etc., with codes stored in them. For each code, there is a column with number of days used days_used1
, days_used2
, days_used3
etc. I want to get a dataframe including a column for each code which has the days_used summed for each of the values in code
.
data.frame(ID = c(1, 2, 3, 4, 5,6),
code1 = c('D', 'D', 'C', 'A', 'G', "A"),
days_used1 = c(NA, NA, 90, 63, 20, 50),
code2 = c('A', 'H', 'D', 'G', 'A', "A"),
days_used2 = c(15, NA, NA, 50, 20, 10),
code3 = c('A', 'H', 'C', 'A', 'D', "D"),
days_used3 = c(15, NA, NA, 50, 20, 10)
)
So i want a dataframe looking like this:
data.frame(ID = c(1, 2, 3, 4, 5),
A= c(30, 0, 0, 20, 60),
D = c(0, 0, 0, 0, 20, 10),
C= c(0, 0, 90, 0, 20, 10),
G= c(0, 0, 0, 50, 20, 0),
H= c(0, 0, 0, 0, 0),
)
I don’t really know how I can get this done. I tried something along the ways of the example below, but this obviously does not work
ifelse(test[paste0("code",c(1:3))] == "A", sum(test[paste0("code",c(1:3)) == "A"]+1), 0)
code1 code2 code3
[1,] 0 0 0
[2,] 0 0 0
[3,] 0 0 0
[4,] 0 0 0
[5,] 0 0 0
[6,] 0 0 0