Hello, Fabricius,

does

as.data.frame( lapply( df, function( x) LETTERS[ x-9]))

what you want?

Other (here maybe less flexible) ways:

transform( df, y = LETTERS[y - 9], z = LETTERS[ z - 9])

within( df, {y <- LETTERS[y - 9]; z <- LETTERS[ z - 9]})

Hth  --  Gerrit


On Fri, 9 Nov 2012, Fabricius Domingos wrote:

Hi R users,

I need a way to substitute the values 10:31 to the letters A:V (i.e 10=A,
11=B, ..., 31=V) in a data frame.

For example:
y<-c(10,11,12,13)
z<-c(28,29,30,31)
df<-data.frame(y,z)
df
  y  z
1 10 28
2 11 29
3 12 30
4 13 31

Then I would substitute it and obtain a data frame like this as a result of
the function:
w<-c("A","B","C","D")     # without actually writing this part down, of
course.
x<-c("S","T","U","V")     # without actually writing this part down, of
course.
df2<-data.frame(w,x)
df2
 w x
1 A S
2 B T
3 C U
4 D V

Apparently the function "replace" can do the job:
attach(df)
replace(y, y==10,"A")
[1] "A"  "11" "12" "13"

But then I would have to do it letter by letter and build the data frame
again. I would not mind doing this for one small data frame but I do have
several large ones, so I was wondering if that's a way that I can write
only one function to perform the action?

I found another way, but it looks kind of silly:
ifelse(y==10,"A", ifelse(y==11,"B", ifelse(y==12,"C", ... )))

Anyway, I would have to rewrite this for every column as well. So what I
really want is something that I could use for the whole data frame (or at
least lapply it), like:
change.to.letters<-function (x) {if x==7 replace(x, x==7, "A")
                     if (x==6) replace(x,x==6,"B")
                       ...................}

                     # and so on... but of course this one does not work,
I just wrote down what I suppose it should looks like. Then I could use:
change.to.letters(y)  # or
lapply(df, FUN=change.to.letters)

Any help would be much appreciated!

Thanks!

   Fabricius

        [[alternative HTML version deleted]]

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


---------------------------------------------------------------------
Dr. Gerrit Eichner                   Mathematical Institute, Room 212
gerrit.eich...@math.uni-giessen.de   Justus-Liebig-University Giessen
Tel: +49-(0)641-99-32104          Arndtstr. 2, 35392 Giessen, Germany
Fax: +49-(0)641-99-32109        http://www.uni-giessen.de/cms/eichner

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to