qzx
qzx

Reputation: 177

R: Data frames: Can the variable name be variable?

The following works:

x <- c(1, 1, 3, 1, 2, 3, 2, 1, 4, 1, 3, 4)
mydat <- data.frame(x)
attach(mydat)
  mydat$x01[x == 1] <- "1"
  mydat$x01[x != 1] <- "not1"
  mydat$x02[x == 2] <- "2"
  mydat$x02[x != 2] <- "not2"
  mydat$x03[x == 3] <- "3"
  mydat$x03[x != 3] <- "not3"
  mydat$x04[x == 4] <- "4"
  mydat$x04[x != 4] <- "not4"
detach(mydat)

However, I want to simplify it to:

x <- c(1, 1, 3, 1, 2, 3, 2, 1, 4, 1, 3, 4)
mydat <- data.frame(x)
attach(mydat)
  for(w in 1:4){
    mydat$paste("x0",w,sep="")[x == w] <- paste(w,sep="")
    mydat$paste("x0",w,sep="")[x != w] <- paste("not",w,sep="")
  }
detach(mydat)

But, this does not work. Is there a way around this?

Upvotes: 1

Views: 31

Answers (1)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193687

You can try something like this:

A <- sort(unique(x))

cbind(mydat, setNames(lapply(A, function(y) {
  replace(x, x != y, paste0("not", y))
}), sprintf("X%02d", A)))
#    x  X01  X02  X03  X04
# 1  1    1 not2 not3 not4
# 2  1    1 not2 not3 not4
# 3  3 not1 not2    3 not4
# 4  1    1 not2 not3 not4
# 5  2 not1    2 not3 not4
# 6  3 not1 not2    3 not4
# 7  2 not1    2 not3 not4
# 8  1    1 not2 not3 not4
# 9  4 not1 not2 not3    4
# 10 1    1 not2 not3 not4
# 11 3 not1 not2    3 not4
# 12 4 not1 not2 not3    4

Upvotes: 1

Related Questions