Home > Enterprise >  R fill specific rows with value from above with added percentage
R fill specific rows with value from above with added percentage

Time:08-25

I am looking to fill in a value in a data frame, fill in the given rows starting at that value down but adding 10% each row.

Here is what I have but it doesn't work.

L3 <- LETTERS[1:3]
fac <- sample(L3, 10, replace = T)
d <- data.frame(x = 0, y = 1:10, fac = fac)

d$x[5] <- 10

d2 <- fill(d$x[6:10], nrow(5))?

CodePudding user response:

d$x[6:10] <- d$x[5] * 1.10^(1:5)
d
#          x  y fac
# 1   0.0000  1   C
# 2   0.0000  2   A
# 3   0.0000  3   B
# 4   0.0000  4   C
# 5  10.0000  5   B
# 6  11.0000  6   B
# 7  12.1000  7   A
# 8  13.3100  8   A
# 9  14.6410  9   B
# 10 16.1051 10   C

The 1:5 is just counting along the desired rows. If you want to automate this a little, then

the_row <- 5
d$x[-seq_len(the_row)] <- d$x[the_row] * 1.10^(seq_len(nrow(d)-the_row))
  •  Tags:  
  • r
  • Related