Very new to R, I know that loops aren't always considered a good option in R but only one part of my code is giving me trouble. Essentially, I'm analysing longitudinal data: each subject has two tables of measures (each table has approx. 200 different study variables) from two different time points. I've read them all in, stored as different variables in R, and am trying to subtract the first table from the second for each participant.
It works fine if I run this as an individual line of code:
data_difference_n <- data_2_n - data_1_n
where n is the participant's ID number, but that would mean running this line for about 1,000 participants whose IDs aren't consecutive numbers. So I've tried to put it inside a loop
participants <- c(100, 105, 106, 119 ...)
for (n in participants) {
...
data_difference_n <- paste("data_difference", subject, sep="_")
data_1_n <- paste("data_1", subject, sep="_")
data_2_n <- paste("data_2", subject, sep="_")
data_difference_n <- data_2_n - data_1_n
}
which gives me an error of "non-numeric argument to binary operator".
Each data table is a CSV with the same properties, mostly numbers and some cells with N/A. The first bit of code gives me the result I want: a new table where all the numerical values are the values in the first table subtracted from the values in the second, for that participant. I'm confused about why the second bit of code doesn't work, because the result should call the same variables as the first?
I've tried reading a lot of other posts about this error here and on other sites but can't seem to resolve it. This one says that using apply converts the data frame to a character matrix, is it the same principle with looping? Feel like I'm missing something really basic and simple here - apologies if so and would appreciate any help!