[R] transform() on selective names. Is it possible?

Juan Carlos Borrás jcborras at gmail.com
Fri Apr 8 11:14:59 CEST 2011


# 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>:
> I haven't stumbled on a solution to that task. I am wondering if you could
> use something like:
>
> inpnames <- names(dfrm) # before the transform step
> outdfrm <- transform(...)
> names(outdfrm) <- c(inpnames, paste(colxy, "new", sep="_") )
>
> .... kludgy to be sure.



More information about the R-help mailing list