-3

I am trying to select column dynamically from a dataframe. Say I have a vector of column names and need to pass that to the dataframe

df_test$c1$c2$c3

Here c2 is what I am trying to pass dynamically. I found a similar question in stackoverflow Dynamically select data frame columns using $ and a vector of column names , but this only talks about df_test$c1 and passing c1 dynamically.

Adding reproducible code

dfList <- split(mtcars, mtcars$cyl)
# the following list the columns mpg,  
dfList$`8`$mpg
dfList$`6`$mpg
dfList$`4`$mpg

#Here I am trying to add 8 ,6 and 4 to a list 
cols <- c("`8`", "`6`","`8`")
#and then pass it to 
dfList$cols[1]$mpg

Is there any way to achieve this?

Gerg
  • 336
  • 4
  • 14
  • What are you trying to achieve with this? are you just trying to select the columns with a vector of column names? Also please provide your data so people have something to work with. – acylam Oct 04 '17 at 02:35
  • 1
    Thanks useR in responding. Yes that is right, But here the c2 is where I want to pass the dynamic list of column names, not to the c1. So I dont know how to go approach of [ ]. – Gerg Oct 04 '17 at 02:38
  • This is unclear. If `df_test` is a data.frame, then that means either `c1` is a column within it, or you are wanting a variable named `c1` to indicate a column to choose. I have no idea what `c2` is supposed to be here. I suggest you [make this question reproducible](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). ("*Pass the dynamic of column names list* to `c2`" still doesn't make sense to me.) – r2evans Oct 04 '17 at 02:39
  • Perhaps you want `df_test[c2]` instead? – r2evans Oct 04 '17 at 02:40
  • 1
    @r2evans c1 is a column list in the dataframe and c2 is another column list within c1 and c3 is the column within the c2 column list. – Gerg Oct 04 '17 at 02:56
  • @useR I am trying to make a reproducible code. – Gerg Oct 04 '17 at 02:57
  • @r2evans and useR Added reproducible code – Gerg Oct 04 '17 at 03:10
  • Why not `dfList[ cols[1] ]`? – r2evans Oct 04 '17 at 03:39
  • yes that works, But how can I select mpg ($mpg)using this way? – Gerg Oct 04 '17 at 03:46
  • ... `dfList[ cols[1] ]$mpg`? – r2evans Oct 04 '17 at 13:04

1 Answers1

1

How about this:

dfList <- split(mtcars, mtcars$cyl)

cols <- c('8', '6','4')

dfList[[cols[[1]]]]$mpg
Alex P
  • 1,574
  • 13
  • 28