简体   繁体   English

"根据 R 中另一列的条件求和(或不求和)一个值"

[英]Sum (or not) a value based on condition of another column in R


Let's imagine the following data. 让我们想象以下数据。 Columns A, B, and C. Column A contains years (eg.2022, 2025, 2030, etc). A、B 和 C 列。A 列包含年份(例如 2022、2025、2030 等)。 Column B contains a month (eg. 2, 7,8, etc). B 列包含一个月(例如 2、7,8 等)。 I need to create a column C that does the following "if else". 我需要创建一个执行以下“if else”的列 C。

If B >=6, then C = A+1. 如果 B >=6,则 C = A+1。
If B is smaller than 6, then C = A. 如果 B 小于 6,则 C = A。

Can anyone help me please? 任何人都可以帮助我吗? Have a good day 祝你有美好的一天"
df$c <- ifelse(df$b >= 6, df$a+1, df$a)

Here is a dplyr<\/code> solution using an ifelse<\/code> statement:这是使用ifelse<\/code>语句的dplyr<\/code>解决方案:

library(dplyr)

df %>% 
  mutate(C = ifelse(B >= 6, A+1, A))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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