r - How to change levels of a variable that is a factor? -


i have data contains numerical values letters, have

j = c( 5 , 6, 7, 6, 7,12 , missing , 6 ,7 8, missing , n/a, n/a, 5, 6)  

i know saved factor number of levels. wanted change n/a 0 numerical value, don't know how that. have used simple commands not let me, data larger have given can not manually.

any appreciated.

the gotcha' factors assignment of value position in vector requires value in levels of factor attribute. can augment acceptable values in 'levels' levels<--function.

> j = factor( c( 5 , 6, 7, 6, 7,12 , 'missing' , 6 ,7, 8, 'missing' , 'n/a', 'n/a', 5, 6)  # notice corrected code since didn't enclose character values in quotes  # ,,,, , seemed missing comma > levels(j) <- c(levels(j), 0)  # append levels; keep initial order. > j[j=='n/a'] <- 0 > j  [1] 5       6       7       6       7       12      missing 6        [9] 7       8       missing 0       0       5       6       levels: 12 5 6 7 8 missing n/a 0 

this exact syntax not apply situation had real r na's rather 'n/a', since nothing ever =='s na.

and looking @ again realized failed see beauty , simplicity of @akrun's suggestion of using level<- modify levels attribute "in place".

 levels(j)[levels(j)=='n/a'] <- 0 

the logic of suggestion has possibly desirable feature of not increasing number of levels integer values in vector remain same 1 needs modify labels within attribute. admit getting tripped factors in r, personal failing apparently still working on.


Comments

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -