I have a specific programming question concerning R. I want to apply a custom function over a whole data set, but the values in the function should change compared to what group it belongs to. Here is a dataset that is similar to the one i'm working with
df <- data.frame(group = c(rep("one", 10), rep("two", 9), rep("three", 11)),
slot = c(1:10, 1:9, 1:11),
x = sample(100, 30))
And the function
RI_fun <- function(x, y) {
((x - y)/ y) * 100
}
The real dataset is larger but the structure is the same. A little info on the real dataset: It is a series of measurements(slots) on a sample (group) where i want the first measurement (slot == 1) to be y in the custom function (RI_fun)
i want to make a new column that is the output of the custom function where x = df$x and y is the x value where df$slot == 1 to each group.
I have tried to make a for loop, but without success. My idea was to make the y value an if else statement where it checked for df$group and applied df$x where slot == 1 and group == group that has just been checked.
Here is my attemp:
for (i in seq_along(df$group)) {
RI[i] = RI_fun(x = df$x[i],
y = (ifelse(df$group == df$group[i],
df$x[df$slot == 1 & df$group == df$group[i]],
NA)))
However the output is:
[1] 0.000000 -61.290323 -78.494624 -3.225806 -30.107527 -87.096774 -8.602151 -54.838710 -68.817204 -93.548387
[11] NA NA NA NA NA NA NA NA NA NA
[21] NA NA NA NA NA NA NA NA NA NA
When i manually checked what the output should be, it showed that the for-loop is correct up to [11] where it doesn't work anymore. I've tried some other for-loops that are similar to this one, but this is the one where i got closest to the desired output.
Any help you got would be appreciated. If i wasn't clear enough, please ask and i'll try to make it more clear.
Aucun commentaire:
Enregistrer un commentaire