Change part of data frame to character, then to numeric in R -


i have simple problem. have data frame 121 columns. columns 9:121 need numeric, when imported r, mixture of numeric , integers , factors. columns 1:8 need remain characters.

i’ve seen people use loops, , others use apply(). think elegant way of doing this?

thanks much,

paul m

try following... apply function allows loop on either rows, cols, or both, of dataframe , apply function, make sure columns 9:121 numeric, can following:

table[,9:121] <- apply(table[,9:121],2, function(x) as.numeric(as.character(x))) table[,1:8] <- apply(table[,1:8], 2, as.character) 

where table dataframe read r.

briefly specify in apply function table want loop on - in case subset of table want make changes to, specify number 2 indicate columns, , give name of as.numeric or as.character functions. assignment operator replaces old values in table new ones of correct format.

-edit: changed first line recalled if convert factor number, integer of factor level , not number think getting factors first need converted characters, numbers, can wrapping as.character inside as.numeric.


Comments

Popular posts from this blog

python - Subclassed QStyledItemDelegate ignores Stylesheet -

java - HttpClient 3.1 Connection pooling vs HttpClient 4.3.2 -

SQL: Divide the sum of values in one table with the count of rows in another -