更新时间:2023-12-01 11:32:10
您不必使用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