[R] General function to substitute values in a data frame
Rui Barradas
ruipbarradas at sapo.pt
Fri Nov 9 11:48:23 CET 2012
Hello,
Try the following. I've changed the name of your data.frame to 'dat',
'df' is an R function.
replace.letter <- function(x, first = 1, upper = TRUE){
if(upper)
LETTERS[x - first + 1]
else
letters[x - first + 1]
}
replace.letter(10:31, first = 10)
y <- c(10,11,12,13)
z <- c(28,29,30,31)
dat <- data.frame(y,z)
apply(dat, 2, replace.letter, first = 10)
Also, the use of attach() is disadvised, it can be confusing.
Hope this helps,
Rui Barradas
Em 09-11-2012 09:33, Fabricius Domingos escreveu:
> 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