vector - Getting Values of Specific Elements of a data frame in R -


i have simple code, not understand why not working way want. basically, have data frame , want capture value of n'th element of column in data frame, , store in vector. here code:

col1_values <- c("abc","xyz","pqr") col2_values <- c("def","jkl","tsm")  means <- data.frame(col1_values,col2_values)  (i in 1:nrow(means)) {     col1_values[i] <- means$col1[i];     col2_values[i] <- means$col2[i]; }  print(means$col1) print(col1_values) 

this outputs:

[1] abc xyz pqr levels: abc pqr xyz [1] "1" "3" "2" 

why not not getting abc xyz tsm in vector col1_values? appears 1, 3, 2 indices of abc xyz tsm in means$col1. need abc xyz tsm in vector col1_values?

thanks.

in r, data.frame() function ships default setting of stringsasfactors=true. means input character vectors implicitly converted called "factors" when creating data.frame.

factor vector integers + text labels describe integers. example, if column gender has type factor vector of integers 1s , 2s plus attached dictionary category id 1 means male , category id 2 means female or vice versa.

this default setting on stringsasfactors sneaky beast , can show in numerous unexpected locations. in of these cases, helps add explicit stringsasfactors=false option keep character vectors character vectors.

below list functions struggled until realising missing stringsasfactors=false option:

  • data.frame
  • read.csv, read.table , other read.* functions
  • expand.grid

in specific example above, need find line:

means <- data.frame(col1_values,col2_values) 

and replace with:

means <- data.frame(col1_values,col2_values,                      stringsasfactors=false) 

such explicitly requesting data.frame() not implicit conversions behind back.

you can avoid conversion changing global option @ beginning of each r session:

options(stringsasfactors = false) 

note, however, modifying global option affects machine , snippets of code may stop working on machines of others.

this answer contains more information how disable permanently.


Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - .htaccess mod_rewrite for dynamic url which has domain names -

Website Login Issue developed in magento -