Reputation: 218
I am trying to learn how to use for loops in R, in particular to subtract a number from it's above number in a column in R.
I know can do this with b <- diff(df$a)
or with:
library(dplyr)
df %>%
mutate(b = a - lag(a))
But I am trying to understand how I can also get the same result with something like:
for(i in 1:nrow(df)){
result = df[2,] - df[i,]
print (result)
}
How do I set this for loop so the df[2,]
takes every following row, and not just the 2nd row, and subtracts from the row above?
For example I have data like this:
column a
1
10
20
and I want to eventually create a column with the subtractions:
column a column b
1 10
11 9
20 ...
Upvotes: 0
Views: 667
Reputation: 388907
You can use for
loop like
df$columnB <- NA
for(i in 1:(nrow(df) - 1)) {
df$columnB[i] = df$columnA[i+1] - df$columnA[i]
}
df
# columnA columnB
#1 1 10
#2 11 9
#3 20 5
#4 25 9
#5 34 NA
data
Sample data used:
df <- data.frame(columnA = c(1, 11, 20, 25, 34))
Upvotes: 2