I would like to loop through the columns in the data frame (from left to right) and find the first value that is equal 1 in each row. If the value is equal 1, then I would like to add a new column to the data frame called x_time = 9,10,11,12 or 13 depending at which time point the value 1 was found first.
See the data example
df <- data.frame(x9 = c('$7', '$7', 2, '$7', 1, '$7'),
x10 = c('$7', 1, '$7', '$7', '$7', '$7'),
x11 = c('$7', '$7', 2, '$7', 1, '$7'),
x12 = c(1, 1, 2, '$7', '$7', '$7'),
x13 = c('$7', '$7', 2, '$7', 2, '$7'))
Desired output:
x9 x10 x11 x12 x13 x_time
1 $7 $7 $7 1 $7 12
2 $7 1 $7 1 $7 10
3 2 $7 2 2 2 NA
4 $7 $7 $7 $7 $7 NA
5 1 $7 1 $7 2 9
6 $7 $7 $7 $7 $7 NA
Please let me know what would the most sufficient approach.
In Stata I would just make a global macro and loop through its content:
global varlist “x09 x10 x11 x12 x13”
gen x_time = .
foreach var in $varlist {
replace x_time = substr("`var'",-2,.) if x_time == . & `var' == 1
}