1

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?

Person
  • 51
  • 1
  • 1
  • 2

2 Answers2

18

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
thelatemail
  • 91,185
  • 12
  • 128
  • 188
C8H10N4O2
  • 18,312
  • 8
  • 98
  • 134
0

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.

  • 1
    Use the same logic, but vectorise it: `ifelse(dat$A < 5, dat$A, ifelse(dat$A==5, 0, ifelse(dat$A==6, dat$B, NA) ))` with test data like `dat <- data.frame(A=c(3,4,5,5,6),B=1:5)` – thelatemail Jul 01 '15 at 00:46