Reputation: 35
I have a following table:
table<- data.frame(a = rep(100, 8),
b = seq(from = 0.2, by = 0.1, length.out = 8))
What I would like to obtain is following column c which has values:
I tried something like code below, but I cannot refer to the new column inside mutate.
table %>% mutate(c = (a + ifelse(is.na(lag(c), 0, lag(c)))) * b)
Some tips?
Thank!:)
Upvotes: 2
Views: 1249
Reputation: 50668
First off: table
is a poor name for a user variable, as it corresponds to a reserved base R function.
Here is a solution using a for
loop.
(Just to preempt any for
loop objections: We're not dynamically growing an object here, and are instead changing pre-initialised entries, so a for
loop will be fast; that's not saying that there won't be any faster ways...):
# Initialise
df <- transform(df, c = a * b);
# Calculate c for rows 2..
for (i in 2:nrow(df)) df$c[i] <- (df$c[i - 1] + df$a[i]) * df$b[i];
df;
# a b c
#1 100 0.2 20.0000
#2 100 0.3 36.0000
#3 100 0.4 54.4000
#4 100 0.5 77.2000
#5 100 0.6 106.3200
#6 100 0.7 144.4240
#7 100 0.8 195.5392
#8 100 0.9 265.9853
df <- data.frame(
a = rep(100, 8),
b = seq(from = 0.2, by = 0.1, length.out = 8))
Upvotes: 1