2021-12-10

Tech Programing

程式人小天地

Performing data frame calculation on all frames in a list using lapply() in R

1 min read


I’m working on a calculation that works for one single data frame:

df <- data.frame(A = c(9,0),
                 B = c(10,1),
                 C = c(6,2),
                 D = c(9,3),
                 E = c(14, 4),
                 F = c(10, 3))

for (i in 1:ncol(df)){
  if (i == 1){df[3:4,1] <- c(0,df[1,1])}
  else{
    df[3,i] <- df[4,i-1]
    df[4,i] <- sum(df[4,i-1], df[1,i]) - df[2,i]
    }
}
df
#  A  B  C  D  E  F
#1 9 10  6  9 14 10
#2 0  1  2  3  4  3
#3 0  9 18 22 28 38
#4 9 18 22 28 38 45

How would I carry this same calculation out if I have a list of data frames?



Source link

資料來源:Stackoverflow

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *