如何使用if语句在R中创建新的数据列? [英] How to create a new column of data in R with if statements?

查看:763
本文介绍了如何使用if语句在R中创建新的数据列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在以下位置创建一个新的数据列D:

I want to create a new column D of data where:

  • 如果A列小于5,则D列= A列
  • 如果A列= 5,则D列= 0
  • 如果A列= 6,则D列= B列

语法是什么?

推荐答案

您不必使用ifelse

df <- data.frame(a=1:6, 
                 b=rep("reproducible",6),
                 c=rep("example",6), stringsAsFactors=F)
df$d <- df$a
df$d[df$a==5] <- 0
df$d[df$a==6] <- df$b[df$a==6]
df
# > df
#   a            b       c            d
# 1 1 reproducible example            1
# 2 2 reproducible example            2
# 3 3 reproducible example            3
# 4 4 reproducible example            4
# 5 5 reproducible example            0
# 6 6 reproducible example reproducible

但是如果您真的愿意,您可以.

But you could if you really want to.

within(df, df$d <- ifelse(a<5, a, 
                        ifelse(a==5, 0,
                               ifelse(a==6,b,NA))) ) #same result

这篇关于如何使用if语句在R中创建新的数据列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆