如何使该选择功能在R中工作?

如何使该选择功能在R中工作?,r,function,dplyr,R,Function,Dplyr,我试图创建一个函数来从数据集中提取某些列。我试过这个: extract <- function(x) { x <- select(filter(df),c(id,x)) } extract(df$var1) extract我想你想做的是 library(dplyr) extract <- function(df, x, id_t){ select(filter(df, id == id_t), x) } 这将选择列2-5,其中id值在df中为20 使用mt

我试图创建一个函数来从数据集中提取某些列。我试过这个:

extract <- function(x) {
 x <- select(filter(df),c(id,x))
}  

extract(df$var1)

extract我想你想做的是

library(dplyr)

extract <- function(df, x, id_t){
   select(filter(df, id == id_t), x)
}
这将选择列2-5,其中
id
值在
df
中为20


使用
mtcars

extract <- function(df, x, id){
   select(filter(df, cyl == id), x)
}
extract(mtcars, 2:5, 6)

#  cyl  disp  hp drat
#1   6 160.0 110 3.90
#2   6 160.0 110 3.90
#3   6 258.0 110 3.08
#4   6 225.0 105 2.76
#5   6 167.6 123 3.92
#6   6 167.6 123 3.92
#7   6 145.0 175 3.62
提取
extract <- function(df, x, id){
   select(filter(df, cyl == id), x)
}
extract(mtcars, 2:5, 6)

#  cyl  disp  hp drat
#1   6 160.0 110 3.90
#2   6 160.0 110 3.90
#3   6 258.0 110 3.08
#4   6 225.0 105 2.76
#5   6 167.6 123 3.92
#6   6 167.6 123 3.92
#7   6 145.0 175 3.62