首页 文章

使用$动态选择数据框列

提问于
浏览
-2

我试图从数据帧动态选择列 . 假设我有一个列名称向量,需要将其传递给数据帧

df_test$c1$c2$c3

这里c2是我试图动态传递的 . 我在stackoverflow Dynamically select data frame columns using $ and a vector of column names中发现了一个类似的问题,但这只涉及df_test $ c1并动态传递c1 .

添加可重现的代码

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

有没有办法实现这个目标?

1 回答

  • 1

    这个怎么样:

    dfList <- split(mtcars, mtcars$cyl)
    
    cols <- c('8', '6','4')
    
    dfList[[cols[[1]]]]$mpg
    

相关问题