I want to create a new column D of data where:
- if column A is less than 5, then column D = column A
- if column A is = 5, then column D = 0
- if column A is = 6, then column D = column B
What would be the syntax?
I want to create a new column D of data where:
What would be the syntax?
You don't have to use 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 you mean the sum of A is greater than 5. Then you can just make a vector for D then make it into a column using rbind()
d <- c()
if(sum(A)<5){
d = A
}else if(sum(A) ==5){
d = 0
}else if(sum(A) == 6){
d = B
}
D <- rbind(d)
I actually don't know if this will work because you haven't covered all your cases, and I don't know exactly what you mean by a column "equalling" 5.