r - Change the class from numeric to factor of many columns in a data frame -
what quickest/best way change large number of columns numeric factor?
i used following code appears have re-ordered data.
> head(stats[,1:2]) rk team 1 1 washington capitals* 2 2 san jose sharks* 3 3 chicago blackhawks* 4 4 phoenix coyotes* 5 5 new jersey devils* 6 6 vancouver canucks* for(i in c(1,3:ncol(stats))) { stats[,i] <- as.numeric(stats[,i]) } > head(stats[,1:2]) rk team 1 2 washington capitals* 2 13 san jose sharks* 3 24 chicago blackhawks* 4 26 phoenix coyotes* 5 27 new jersey devils* 6 28 vancouver canucks*
what best way, short of naming every column in:
df$colname <- as.numeric(ds$colname)
further ramnath's answer, behaviour experiencing due as.numeric(x)
returning internal, numeric representation of factor x
@ r level. if want preserve numbers levels of factor (rather internal representation), need convert character via as.character()
first per ramnath's example.
your for
loop reasonable apply
call , might more readable intention of code is. change line:
stats[,i] <- as.numeric(stats[,i])
to read
stats[,i] <- as.numeric(as.character(stats[,i]))
this faq 7.10 in r faq.
hth
Comments
Post a Comment