Skip to content
Prev 310377 / 398506 Next

General function to substitute values in a data frame

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? 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:
course.
course.
? w x
1 A S
2 B T
3 C U
4 D V

Apparently the function "replace" can do the job:
[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:
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:
? ? ? ? ? ? ? ? ? ? ? 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:
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.