簡體   English   中英

在 R 中的 data.table 中使用 ifelse 來賦值

[英]using ifelse in data.table in R to assign values

讓我們想象一下,我想從mtcars包中創建一個包含三列的mtcars 我想要按gear分組的cost (出於說明目的,它是 hp 的總和)。 問題是第三個變量costlimited - 它取決於先前指定的budget 如果cost > budget ,則cost costlimited = budget ,否則cost costlimited = cost

budget <- c(2000)
mtcarsTOTAL <- mtcars[, ':=' ( cost = sum(hp), costlimited = ifelse(cost > budget, budget, cost) ), by = gear] 

此外,我想添加一列,如果成本 > 預算,則為 1,否則為 0。 想要的結果是

    gear cost costLimited highCost
[1,]    4 1074        1074        0
[2,]    3 2642        2000        1
[3,]    5  978         978        0

重點是在 data.table 中做到這一點,我目前正在邊做邊學。

這里不需要ifelse (順便說一句, fifelsedata.table 。)

嘗試

library(data.table)
budget <- c(2000)

dt <- as.data.table(mtcars)[, .(cost = sum(hp)), by = gear]
dt[, costlimited := pmin(budget, cost)]
dt[, highCost := +(budget == costlimited)]
dt
#   gear cost costlimited highCost
#1:    4 1074        1074        0
#2:    3 2642        2000        1
#3:    5  978         978        0

這有幫助嗎?

budget <- c(2000)

mtcars <- tibble(
  gear = c(4, 3, 5), 
  cost = c(1074, 2642, 978 ) 
)

mtcarsTOTAL <- mtcars
mtcarsTOTAL$costLimited <- ifelse(mtcarsTOTAL$cost > budget, budget, mtcarsTOTAL$cost )
mtcarsTOTAL$highCost <- ifelse(mtcarsTOTAL$cost > budget, 1, 0 )

暫無
暫無

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

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