Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用数据帧列表中的数据帧作为R中的函数参数,并按其名称调用它_R_Function_Dataframe_Arguments - Fatal编程技术网

使用数据帧列表中的数据帧作为R中的函数参数,并按其名称调用它

使用数据帧列表中的数据帧作为R中的函数参数,并按其名称调用它,r,function,dataframe,arguments,R,Function,Dataframe,Arguments,嘿,我最近问了一个我用词很糟糕的问题,所以我想用一个更好的例子再问一次。假设我有一个数据帧列表,如下所示: first<- data.frame(b = factor(c("Hi", "Med", "Hi", "Low"), levels = c("Low", "Med", "Hi"), ordered = TRUE), x = c("A", "D", "A", "C"), y = c(8, 3, 9, 9), z = c

嘿,我最近问了一个我用词很糟糕的问题,所以我想用一个更好的例子再问一次。假设我有一个数据帧列表,如下所示:

first<- data.frame(b = factor(c("Hi", "Med", "Hi", "Low"), 
           levels = c("Low", "Med", "Hi"), ordered = TRUE),
           x = c("A", "D", "A", "C"), y = c(8, 3, 9, 9),
           z = c(1, 1, 1, 2))
second<- data.frame(b = factor(c("Med", "Med", "Low", "Low"), 
           levels = c("Low", "Med", "Hi"), ordered = TRUE),
           x = c("c", "B", "C", "D"), y = c(3, 2, 6, 5),
           z = c(1, 11, 4, 3))

c<- list(first,second)
现在的问题是,我想让数据帧列表中的数据帧成为函数中的参数。它将改为:

test<- function(arg0, arg1){
  poop<- subset(c$arg0, c$arg0$b=="Med")
  pee<- mean(poop[,arg1])
  return(pee)
}

当我想再次获得2.5分时。我希望通过列表中的名称来调用数据帧,而不是通过任何指定的元素号。谢谢

我们可以尝试使用
[

test<- function(arg1, arg2){
   poop <- subset(c[[arg1]], b=='Med')
   mean(poop[[arg2]])
}

test("second", "y")
#[1] 2.5

testIt不建议在函数内部使用
$
。请使用
[
test("y")
[1] 2.5
test<- function(arg0, arg1){
  poop<- subset(c$arg0, c$arg0$b=="Med")
  pee<- mean(poop[,arg1])
  return(pee)
}
test("second","y")
[1] NA
Warning message:
In mean.default(poop[, arg1]) :
  argument is not numeric or logical: returning NA
test<- function(arg1, arg2){
   poop <- subset(c[[arg1]], b=='Med')
   mean(poop[[arg2]])
}

test("second", "y")
#[1] 2.5
test<- function(arg1, arg2){
   Call <- as.list(match.call())[-1]
   nm1 <- sapply(Call, deparse)
  mean(subset(c[[nm1[1]]], b=="Med")[[nm1[2]]])
}

test(second, y)
#[1] 2.5