0

Let' s say that :

colstr="mycol"

Now, for a given df that contains a column named mycol, I want to do the following :

myfactors <- factor(df$colstr)

This does not work as the command is executed as:

myfactors <- factor(df$"mycol")

istead of the correct :

myfactors <- factor(df$mycol)

How can I correct this?

Tassos Pan
  • 23
  • 5
  • This [answer](https://stackoverflow.com/questions/18222286/dynamically-select-data-frame-columns-using-and-a-character-value) might help? – Quinten Dec 23 '22 at 10:02
  • `factor(df[colstr])`. – user2974951 Dec 23 '22 at 10:02
  • 3
    You can't use the `$` notation that way. The variable after the `$` is always read as-is, and not substitued. To get the correct column if the name is stored as a character is `df[colstr]`, which will be the same as `df$mycol` – Allan Cameron Dec 23 '22 at 10:04

1 Answers1

0

Make sure df is a data.frame and you are good to go. I used the following example and it worked for me:

df <- data.frame(x=1:10, mycol=letters[1:10])
myfactors <- factor(df$mycol)
myfactors

Here's the output:

 [1] a b c d e f g h i j
Levels: a b c d e f g h i j

In a data frame, there is no need to use quotation or double-quotation to call a column (variable).

Afshin
  • 103
  • 6