[R] General function to substitute values in a data frame

arun smartpink111 at yahoo.com
Fri Nov 9 14:27:35 CET 2012


HI,
May be this:
res<- data.frame(apply(df,2,function(x) ifelse(grepl("\\d+",x),LETTERS[x-9],NA)))
res
#  y z
#1 A S
#2 B T
#3 C U
#4 D V
#or
 apply(df,2,function(x) LETTERS[x-9])
A.K.





----- Original Message -----
From: Fabricius Domingos <fabriciusm at gmail.com>
To: r-help at r-project.org
Cc: 
Sent: Friday, November 9, 2012 4:33 AM
Subject: [R] General function to substitute values in a data frame

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 at 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.





More information about the R-help mailing list