簡體   English   中英

如何使用條件減去 R 中的多列

[英]How to subtract multiple columns in R with condition

我有一個看起來像這樣的數據集。 在我的新數據集中,我想用主列和余數列減去金額列。

例如,如果amount列是 4, principal列是 2, remainder是 3,則必須從第一個主列和第一個余數列中減去第一個金額列,第 2 個與第 2 個主列和第 2 個余數列相減,第 3 個與第三個余數列(因為現在沒有更多的主列)。 最后一個 amount4 列必須保持原樣 newamount4

amount1  amount2   amount3 amount4  principal1  principal2  remainder1  remainder2    remainder3  
 100      250       150    100           250       100         80         100          100 
 200      200       350    25            450       100        120         100          50
 300      150       450    30            200       100        150         100          100
 250      550       550    100           100       200         50         500          200
 550      200       650    200          250       200        500         100          500

我的新數據集必須如下所示。 請注意am代表金額pr代表本金, rem代表余數

 newamount1          newamount2         newamount3     newamount4       
 20(am1-pr1-rem1)    150(am2-pr2-rem2)  50(am3-rem3)   amount4        
 80                  100                300            amount4        
 150                 50                 350            amount4        
 200                 50                 350            amount4        
 50                  100                100            amount4        

我的代碼包括以下腳本,我試圖通過該腳本獲得所需的 output。 我的 dataframe 被命名為修訂版

am_cols <- grep('amount_', names(revised)) 
rm_cols <- grep('principal_', names(revised)) 
sm_cols <- grep('remainder_', names(revised))

revised[is.na(revised)] <- 0


result <- cbind(revised[head(am_cols, rm_cols, length(sm_cols))] - revised[rm_cols] - revised[sm_cols], 
                revised[head(am_cols, length(rm_cols))] - revised[sm_cols], 
                revised[tail(am_cols, -length(rm_cols), -length(sm_cols))]) 

我們可以使用split.default

lst1 <- lapply(split.default(df1,
        sub("\\D+", "", names(df1))), function(x) Reduce(`-`, x))
df1[paste0('newamount', seq_along(lst1)] <- lst1  

數據

df1 <- structure(list(amount1 = c(100L, 200L, 300L, 250L, 550L), amount2 = c(250L, 
200L, 150L, 550L, 200L), amount3 = c(150L, 350L, 450L, 550L, 
650L), amount4 = c(100L, 25L, 30L, 100L, 200L), principal1 = c(250L, 
450L, 200L, 100L, 250L), principal2 = c(100L, 100L, 100L, 200L, 
200L), remainder1 = c(80L, 120L, 150L, 50L, 500L), remainder2 = c(100L, 
100L, 100L, 500L, 100L), remainder3 = c(100L, 50L, 100L, 200L, 
500L)), class = "data.frame", row.names = c(NA, -5L))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM