Skip to content
Back to formatted view

Raw Message

Message-ID: <1239908331.10629.26.camel@lynx.ibmt.intern>
Date: 2009-04-16T18:58:51Z
From: Juergen Rose
Subject: Translate the elements of a dataframe

The second beginner question. I want to create a new dataframe, where
each element of the original dataframe is translated to 1 if it was "+",
to 0 if it was "-" to -1 otherwise. I could do with:

Lines <- "a    b    c    d
    +    -    +   +
    +    +    +   -   
    +    1    -   '+ '
    -    +    +   +
    +    N    -   +"


DF <- read.table(textConnection(Lines), header = TRUE)
cnames <- colnames(DF)
nrow <-length(rownames(DF))

nc <- length(cnames)
NDF <- data.frame(matrix(c(rep(0,nc*nrow)),ncol=nc))

for (i in 1:length(cnames)) {
  NDF[,i] <- sapply(DF[,i],function(x) if (x=="+") {1} else {if (x=="-")
{0} else {-1}} )
}
colnames(NDF) <- cnames

But this is shure one loop too much. Please give me the R way solution.