在 R. 中,有条件地添加变量之一必须为正的值使用 rowsums

问题描述

我之前使用过以下代码添加行的值:

subset$EBIT <- rowSums(subset[c("rorresul","resand","rteinknc","rteinext","rteinov")],na.rm = TRUE)

但是,我实际上需要包含这样一个条件,即只有在它是正数时才应包含“重砂”。其他值可以是正值也可以是负值,这无关紧要。我使用了 rowSums,因为否则,如果其中一个变量中存在缺失值,那么我的总数最终会出现缺失值。

如果您需要数据样本,这里有一些:

rorresul  resand  rteinknc  rteinext  rteinov
  40        30       2         2         2
  50        -40      5         5         5
  30         0       1         1         1

非常感谢任何帮助!谢谢!

解决方法

我只是将所有内容相加,然后减去重沙:

library(dplyr)

df %>% 
  mutate(
    EBIT = rowSums(across(everything())),EBIT = ifelse(resand < 0,EBIT - resand,EBIT)
  )

#   rorresul resand rteinknc rteinext rteinov EBIT
# 1       40     30        2        2       2   76
# 2       50    -40        5        5       5   65
# 3       30      0        1        1       1   33

这是数据:

df <- data.frame(
  rorresul = c(40,50,30),resand = c(30,-40,0),rteinknc = c(2,5,1),rteinext = c(2,rteinov = c(2,stringsAsFactors = FALSE
)

编辑 如果您有不应包含在 rowSums 中的变量,那么您可以预先指定这些:

sumVars <- c("rorresul","resand","rteinknc","rteinext","rteinov")

df %>% 
  mutate(
    EBIT = rowSums(across(all_of(sumVars))),EBIT)
  )
,

您可以使用 pmaxresand 的负值变为 0 并计算 rowSums

cols <- c("rorresul","rteinov")
df$EBIT <- rowSums(transform(df,resand = pmax(resand,0))[cols])
df
#  rorresul resand rteinknc rteinext rteinov EBIT
#1       40     30        2        2       2   76
#2       50    -40        5        5       5   65
#3       30      0        1        1       1   33