如何使用if语句在R中创建新的数据列?

Per*_*son 0 if-statement r

我想创建一个新的数据列D,其中:

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

语法是什么?

C8H*_*4O2 14

你不必使用 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
Run Code Online (Sandbox Code Playgroud)

但你可以,如果你真的想.

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