I have a dataframe structured like the following, with the number of x_L
and x_R
pair being possibly up to 100.
ID Side A_L A_R B_L B_R
1 0 7 5 6 3
2 1 3 2 3 1
3 0 6 3 4 5
I know want to create a new column A_ratio
for each pair A_L
and A_R
. The value of that new column for each ID should either be A_L / A_R
if Side==0
, or A_R / A_L
if Side==1
.
My attempt was implementing a for
loop with an increment of 2, to cover each pair only once, and using ifelse
to differentiate between the two possible values of Side
for (i in seq(from = 3, to = length(df), by = 2)) {
df[sub("_L", "_ratio",(names(df[i]))] <-ifelse(df[2]==0, df[i] / df[i+1], df[i+1] / df[i])
}
This however leads to the following warning:
In `[<-.data.frame`(`*tmp*`, sub("_L", "_ratio", names(df[i])), : provided 3 variables to replace 1 variables
The resulting values seem to be A_L / A_R
for all cases, even for the IDs with Side==1
. Could someone point out my mistake?
I know that there should be an easier dplyr
approach as well, but I'm unfortunately not familiar with that yet.
Thanks in advance!