首页 > 解决方案 > 在列表上迭代函数

问题描述

我有一个要沿变量拆分的数据框列表。我试图通过创建一个函数来自动化这个过程。我知道有一个名为 split 的函数可以执行此操作,但我正在尝试学习如何创建函数,因此我将其用作练习。

以下是一些示例数据:

Area <- c(1, 5, 5 ,7, 2) 
Protected <- c('protected', 'protected', 'protected', 'unprotected', 'unprotected')
a_data <- data.frame(Area, Protected)

Area <- c(6, 2, 7, 2, 9)
Protected <- c('protected', 'protected', 'protected', 'unprotected', 'unprotected')
b_data <- data.frame(Area, Protected)

我想将这些中的每一个沿着变量“受保护”拆分,留下四个数据帧 p_a、p_b、u_a 和 u_b。

到目前为止,我的代码是这样的:

names <- list('a', 'b')

f <- function(x){
  for(i in names){
    d <- paste(i,'_data', sep = '')
    p_'i' <- subset(d, Protected == 'protected')
    u_'i' <- subset(d, Protected == 'unprotected')
  }
}

这不会运行,我很确定这是因为我试图将 i 的当前迭代分配给变量的名称,同时还试图为其分配值。

我该如何解决这个问题?

标签: r

解决方案


稍微改变你的功能的一个想法是将数据框放在一个列表中并直接迭代,即

lapply(list(a_data, b_data), function(i) { d1 <- subset(i, Protected == 'protected');
                                           d2 <- subset(i, Protected == 'unprotected'); 
                                           return(list(d1, d2))})

这使,

[[1]]
[[1]][[1]]
  Area Protected
1    1 protected
2    5 protected
3    5 protected

[[1]][[2]]
  Area   Protected
4    7 unprotected
5    2 unprotected


[[2]]
[[2]][[1]]
  Area Protected
1    6 protected
2    2 protected
3    7 protected

[[2]][[2]]
  Area   Protected
4    2 unprotected
5    9 unprotected

推荐阅读