[R] Re categorizing components of varaibles
JS Huang
js.huang at protective.com
Wed Feb 18 00:35:19 CET 2015
Hi,
Here I use the data.frame b as an example to show how it can be
accomplished. The sixth column of b has values 6 through 996 by an
increment of 10. The statement
sapply(b[,6],function(x)if(x==6){0}else{if(x==996){2}else{1}}) assigns 0 to
6, 2 to 996 and 1 to the rest in column 6. In your case you may use
sapply(b[,6],function(x)if(x==24){2}else{if(x==26){3}else{1}})
(Note: did you forget to assign a value to 25?)
> a <- matrix(1:1000, ncol=10, byrow=TRUE)
> b <- data.frame(a)
> b[,6] <- sapply(b[,6],function(x)if(x==6){0}else{if(x==996){2}else{1}})
> b <- data.frame(a)
> b[,6]
[1] 6 16 26 36 46 56 66 76 86 96 106 116 126 136 146 156 166
176 186 196 206 216 226 236
[25] 246 256 266 276 286 296 306 316 326 336 346 356 366 376 386 396 406
416 426 436 446 456 466 476
[49] 486 496 506 516 526 536 546 556 566 576 586 596 606 616 626 636 646
656 666 676 686 696 706 716
[73] 726 736 746 756 766 776 786 796 806 816 826 836 846 856 866 876 886
896 906 916 926 936 946 956
[97] 966 976 986 996
> b[,6] <- sapply(b[,6],function(x)if(x==6){0}else{if(x==996){2}else{1}})
> b[,6]
[1] 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1
[50] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1
[99] 1 2
--
View this message in context: http://r.789695.n4.nabble.com/Re-categorizing-components-of-varaibles-tp4703424p4703434.html
Sent from the R help mailing list archive at Nabble.com.
More information about the R-help
mailing list