在函数中子集数据帧

问题描述 投票:0回答:2

我正在努力用函数引用列。

拿数据:

  dat = data.frame(height = c(20, 20, 40, 50, 60, 10), weight = c(100, 200, 300, 200, 140, 240),
               age = c(19, 20, 20, 19, 10, 11))
  Age_list <- c(19)

举个例子:

toy_func <- function(df,list,column){

  for (i in list){
  toy_output <- df[,column == i]
  }

  Return(toy_output)
}

并运行:

tst <- toy_func(dat,Age_list,"age")

输出是没有变量的数据帧。我想生成一个输出,其中初始数据帧dat已被过滤年龄等于19。

循环是必要的,因为我打算迭代年龄列中的每个唯一项。本质上,我正在编写一个函数来按照其中一列中的唯一值对数据帧进行分区。

先谢谢你,约翰

r
2个回答
2
投票

使用@phiver的建议,你可以试试这个:

dat = data.frame(height = c(20, 20, 40, 50, 60, 10),
                 weight = c(100, 200, 300, 200, 140, 240),
                 age = c(19, 20, 20, 19, 10, 11))
Age_list <- c(19,20)

for (i in Age_list){
  toy_output <- split(dat,dat$age==i)$`TRUE`
  print(toy_output)
  }

结果:

  height weight age
1     20    100  19
4     50    200  19
  height weight age
2     20    200  20
3     40    300  20

编辑:

您可以执行一个简单的解决方法将其放入函数中:

toy_func <- function(df,list,x){

for (i in list){
  toy_output <- split(df,df[,x]==i)$`TRUE`
  print(toy_output)
              }
           }

toy_func(dat,Age_list ,3)

  height weight age
1     20    100  19
4     50    200  19
  height weight age
2     20    200  20
3     40    300  20

Aaditi:

这将给你一个带结果的data.framei列告诉你哪一个迭代生成每一行:

toy_func <- function(df,list,x){
   datalist = list()
        for (i in list){
            toy_output <- data.frame(split(df,df[,3]==i)$`TRUE`)
            toy_output$i <- i
            datalist[[i]] <- toy_output
                       }
   print(do.call(rbind, datalist))
  }

toy_func(dat,Age_list ,3)

  height weight age  i
5     60    140  10 10
2     20    200  20 20
3     40    300  20 20

0
投票

你可以试试

foo <- function(x, y, z) x[ x[[y]] %in% z, ]
foo(dat, "age", c(19, 20))
  height weight age
1     20    100  19
2     20    200  20
3     40    300  20
4     50    200  19

如果您需要输出作为排序列表,您可以编写

lapply(c(19,20), foo, x=dat, y="age")
[[1]]
  height weight age
1     20    100  19
4     50    200  19

[[2]]
  height weight age
2     20    200  20
3     40    300  20
© www.soinside.com 2019 - 2024. All rights reserved.