简体   繁体   中英

Subtract an observation from another in different column and add a specific value to the result to create a new observation in the first column in R

I have something like this,

A    B     C 
100  24      
     18
     16
     21
     14

I am trying to write a function that calculates C = AB for the respective row and then adds 20 to C which is A for the next row and repeats the step and it should be like this at the end.

A     B     C
100   24    76
96    18    78
98    16    82
102   21    81
101   14    87

I am doing it manually atm like
df$C[1] = df$A[1] - df$B[1] and then
df$A[2] = df$C[1]+20 and repeating it.
I would like to create a function instead of doing this way. Any help would be appreciated.

Here is another approach using for loop:

data

df <- data.frame(A=NA, B = c(24L, 18L, 16L, 21L, 14L),C=NA)

Initialize first row of df

df$A[1] <- 100
df$C[1] <- df$A[1]-df$B[1]

Populate the remaining rows of df

for (i in 1:(length(df$B)-1)){
df$C[i+1]   <- df$C[i]-df$B[i+1]+20
df$A[i+1]   <- df$C[i]+20 
}

Output

df
   A  B  C
1 100 24 76
2  96 18 78
3  98 16 82
4 102 21 81
5 101 14 87

We can start with only B column and then calculate A and C respectively.

start_value <- 100
df$A <- c(start_value, start_value - cumsum(df$B) + 20 * 1:nrow(df))[-(nrow(df) + 1)]
df$C <- df$A - df$B
df

#   B   A  C
#1 24 100 76
#2 18  96 78
#3 16  98 82
#4 21 102 81
#5 14 101 87

data

df <- structure(list(B = c(24L, 18L, 16L, 21L, 14L)), 
     class = "data.frame", row.names = c(NA, -5L))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM