简体   繁体   English

IF ELSE语句中的多个动作

[英]Multiple actions in IF ELSE statement

A sample data frame looks like this: 示例数据框如下所示:

df = data.frame(a=1:5, b=11:15)
a  b
1 11
2 12
3 13
4 14
5 15

How do I use if else statement to create new column c and d in the data frame? 如何使用if else语句在数据框中创建新的列c和d? I want the output to look like this: 我希望输出看起来像这样:

a b    c    d
1 11 'yes'  22
2 12 'yes'  24
3 13 'yes'  26
4 14 'no'   14
5 15 'no    15

I've tried this according to ( If statement with multiple actions in R )! 我已经尝试过根据( If语句在R中有多个动作 )进行尝试!

for (i in nrow(df)){
  if (df$a[i] <4) {
    df$c[i] = 'yes'; 
    df$d[i] = df$b[i]*2;
    df
  } else {
    df$c[i] = 'no'; 
    df$d[i] = df$b[i];
    df
  }
}

But the output only provide the last row: 但是输出仅提供最后一行:

 a  b   c  d
 1 11 <NA> NA
 2 12 <NA> NA
 3 13 <NA> NA
 4 14 <NA> NA
 5 15   no 15

Thanks in advance. 提前致谢。

Another vectorized solution using ifelse() : 使用ifelse()另一个矢量化解决方案:

df$c <- ifelse(df$a < 4, 'yes', 'no')
df$d <- ifelse(df$a < 4, df$b*2, df$b)

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

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