Skip to main content
 首页 » 编程设计

r中如何传递 R 函数参数以从 df 中选择行

2025年01月19日65insus

我正在尝试编写一个函数,该函数允许我在 df 的“x”列中指定一个或多个值,以便我的结果仅包含具有这些 x 值的行。我计划稍后向该函数添加其他参数,但这是第一步。

x<-c(1:100) 
y<-rnorm(100) 
df<-as.data.frame(cbind(x,y)) 
myfunc<-function(x=1:100){ 
result<-subset(df,select=x) 
result 
} 

当我运行以下代码来获取 4 行 df 时,结果是 100 行,只有 x 列:

> myfunc(x==3:6) 
      x 
1     1 
2     2 
3     3 
4     4 
5     5 
.... 
99   99 
100 100 

myfunc(x=3:6) 和 myfunc(3:6) 也不起作用

请您参考如下方法:

我会像这样编辑你的函数:

myfunc <- function(z = 1:100){ 
  result <- subset(df, x %in% z) 
  result 
} 
 
myfunc(z = 3:6) 
#   x          y 
# 3 3  0.7585295 
# 4 4 -0.2713343 
# 5 5  0.5359432 
# 6 6 -0.4653105