1

I have a data-set with following column names:

> colnames(newdat1)
[1] "i4" "i2" "i3" "i1" "b4" "b3" "b2" "b1"

I also have a variable "newDV" which will always be the column name of the dependent variable if newdat1

> newDV
[1] "i1"

How can I get the column in newdat1 that corresponds to whatever newDV is? The idea being I don't want to have to manually type the item newDV corresponds to, such as newdat1$i1 in this case. I have tried the following

> gettheDV<-paste("newdat1",newDV,sep="$",collapse="")
> gettheDV
[1] "newdat1$i1"

I am not sure if this is on the right track, but any help would be appreciated. Thank you!

costebk08
  • 1,299
  • 4
  • 17
  • 42

1 Answers1

0

Ok, data.frame 101!

newdat1[, newDV] or newdat1[[newDV]] should do it. Credit also to user Alex A.

(Bonus explaining: the first syntax will accept a vector of column names if you want to return multiple columns. The latter is to retrieve a single column only, and is also useful for dealing with lists generally, of which data.frame are basically a special case. There's lots more detail in the basic R documentation)

arvi1000
  • 9,393
  • 2
  • 42
  • 52