0

I have a sample dataframe below df.

    df
     ColA       ColB      ColC
      A           B         2
      D           B         3
      D           A         4

To get values in ColA, we can use df$ColA. But can we not reference here. For example

    sa <- names(Filter(is.factor,df))
    sa 
    sa
   [1] "ColA" "ColB"

If I use the below code, I am not getting elements of ColA. Should be getting right? Or is there way to do this

     df$sa[1]
Dev P
  • 449
  • 3
  • 12

1 Answers1

0

We can't reference columns with $ when having sa as character vector. We can do

df[sa[1]]

#  ColA
#1    A
#2    D
#3    D

Or with dplyr

library(dplyr)
df %>% select(sa[1])
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213