[R] Replace a variable by its value

Rui Barradas ruipbarradas at sapo.pt
Mon May 21 14:11:02 CEST 2012


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
> 
> I have a dataset called "raw-data" . I am trying to use the following code
> -
> 
> 
> col_name<-names(raw_data)
> for (i in 1:(length(names(raw_data))-2))
> {
>   tbl=table(raw_data$Pay.Late.Dummy, raw_data$col_name[i])
>   
>   chisqtest<-chisq.test(tbl)
> }
> 
> 
> Say the 1st column of my raw_data is Column1. The idea is when i=1 then
> raw_data$col_name[i] will automatically become raw_data$Column1 , which is
> not happening. Kindly help?
> 


--
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.



More information about the R-help mailing list