[R] Reclassifying values within a vector to several other values

Petr Pikal petr.pikal at precheza.cz
Tue Nov 29 11:28:28 CET 2005


Hi

On 29 Nov 2005 at 9:42, Roy Sanderson wrote:

Date sent:      	Tue, 29 Nov 2005 09:42:12 +0000
To:             	r-help at stat.math.ethz.ch
From:           	Roy Sanderson <R.A.Sanderson at newcastle.ac.uk>
Subject:        	[R] Reclassifying values within a vector to several other values

> Dear List
> 
> Apologies for such a simple question:
> 
> I have a vector of 738 elements, coded with values between 1 and 16
> (but not containing 7, 10, 11 or 13) and wish to recode value 14 to 1,
> 4 to 2, 1 to 3, 2 to 4 and all other values to 5.  I've been trying to
> use the replace function (in base) and %in%, but without success.

Try to use factor.

test<-sample(1:16, 1000, replace=T)
test<-test[!test%in%c(7,10,11,13)]
test.f<-as.factor(test)
levels(test.f)
 [1] "1"  "2"  "3"  "4"  "5"  "6"  "8"  "9"  "12" "14" "15" "16"
levels(test.f)<-c(3,4,5,2,5,5,5,5,5,1,5,5)
 levels(test.f)
[1] "3" "4" "5" "2" "1"
tapply(test,test.f,mean)
        3         4         5         2         1 
 1.000000  2.000000  9.281496  4.000000 14.000000

If you want it numeric use as.numeric(as.character()) conversion.

HTH
Petr



> 
> Many thanks
> Roy
> ----------------------------------------------------------------------
> ------ ------- Roy Sanderson Institute for Research on Environment and
> Sustainability Devonshire Building University of Newcastle Newcastle
> upon Tyne NE1 7RU United Kingdom
> 
> Tel: +44 191 246 4835
> Fax: +44 191 246 4998
> 
> http://www.ncl.ac.uk/environment/
> r.a.sanderson at newcastle.ac.uk
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide!
> http://www.R-project.org/posting-guide.html

Petr Pikal
petr.pikal at precheza.cz




More information about the R-help mailing list