Skip to content
Prev 256217 / 398506 Next

transform() on selective names. Is it possible?

# The code demonstrating the final version I am going to use is as follows

rm(list=ls()) # Beware of this one so it doesn't spoil your workspace

N <- 100
M <- 2
x <- matrix(data=rnorm(N*M, 0, 3)-10, ncol=M, nrow=N)
y <- matrix(c(1,-2,-2,1), ncol=M, nrow=M)
z <- data.frame(x %*% y)
colnames(z) <- c('x','y')
par(mfrow=c(1,4))
plot(z, pch=3, col="black")

withen <- function(dfrm, coln) {
  x <- transform(dfrm, coln=scale(dfrm[,coln]))
  if (length(coln)==1) {
    y <- x
    y[,coln] <- NULL
    colnames(y) <- sub("^coln",coln,colnames(y))
  } else {
    y <- x[,grep("^coln", colnames(x))]
    colnames(y) <- sub("^coln.","",colnames(y))
  }
  return(y)
}

colx <- c("x")
coly <- c("y")
colxy <- c("x", "y")

z1 <- withen(z, colx)  # the "[" function will interpret colxy
plot(z1, pch=5, col="magenta")

z2 <- withen(z, colxy)  # the "[" function will interpret colxy
plot(z2, pch=7, col="green")

z3 <- withen(z, colxy)  # the "[" function will interpret colxy
plot(z3, pch=9, col="blue")

#Cheers,
#jcb!

2011/4/7 David Winsemius <dwinsemius at comcast.net>: