Hi everyone and thank you for reading.
I've been stuck in trying to create a function that will iteratively subtract the values of two columns and paste the value in a new column. To show what I mean here is an example with the starting dataset:
Sample g1 g2 g3 g4 g5
s001 5 10 15 20 25
s002 6 11 16 21 26
s003 7 12 17 22 27
s004 8 13 18 23 28
Let's say I would like choose g3. I would then like to subtract all the other columns from g3, but have the values show up in a new column right next to each one. Essentially the end result would look like this:
Sample g1 g1dt g2 g2dt g3 g3dt g4 g4dt g5dt g5dt
s001 5 10 10 5 15 0 20 -5 25 -10
s002 6 10 11 5 16 0 21 -5 26 -10
s003 7 10 12 5 17 0 22 -5 27 -10
s004 8 10 13 5 18 0 23 -5 28 -10
The code I tried looked like this:
for (i in 2:6) {
dt <- paste0(names(dataset)[i]) #where names(dataset) is the ith name
#from dataset
dataset[[dt]] <- dataset$g3 - dataset[[,2:6]] #[[]] is
#supposed to create a new column "dt" added as a suffix
}
This however results in the following error:
Error in .subset2(x, ..2, exact = exact) :
recursive indexing failed at level 3
Any idea on what I could otherwise try? Please let me know if I need to clear up any confusing matters. Thanks!