Skip to content
Prev 295153 / 398506 Next

Replace a variable by its value

Hello,

Your doubt is a frequent one. 'col_name' is a character vector, it's
elements are character strings, not symbols.
These are all equivalent, and are what you want.

raw_data[[ col_name[i] ]]  # using a list-like syntax (data.frame subclasses
list)
raw_data[ , col_name[i] ]  # seems more like a rows&columns data structure
raw_data[ , i ]  # using the column number

Two notes.
One, it's better to use seq.int than to use 1:length(...) because if the
length is zero, the second form will become the vector 1:0 == c(1, 0) and
your loop will execute with wrong results. See the help page for seq.int

?seq.int
seq.int(length(col_name) - 2)


The other, you're rewriting the value of 'chisqtest' every time through the
loop. If you only want the test results inside it, that's ok, if not, maybe
you could keep the results in a list, using something like


chisqtest <- vector("list", length(col_name) - 2)  # create the list before
the loop
for (i in seq.int(length(col_name) - 2))
{ 
      [... loop code ...]

      chisqtest[[ i ]] <- chisq.test(tbl) 
}


Hope this helps,

Rui Barradas

anindya55 wrote
--
View this message in context: http://r.789695.n4.nabble.com/Replace-a-variable-by-its-value-tp4630734p4630736.html
Sent from the R help mailing list archive at Nabble.com.