r - 在列表上迭代函数
问题描述
我有一个要沿变量拆分的数据框列表。我试图通过创建一个函数来自动化这个过程。我知道有一个名为 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 的当前迭代分配给变量的名称,同时还试图为其分配值。
我该如何解决这个问题?
解决方案
稍微改变你的功能的一个想法是将数据框放在一个列表中并直接迭代,即
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
推荐阅读
- laravel - 尝试从 Laravel 8 控制台命令(Windows 10)上传到 Google Cloud Storage 时“无法打开流:权限被拒绝”
- java - 如何在 WebClient Springboot 中处理“io.netty.channel.unix.Errors$NativeIoException: readAddress(..) failed: Connection reset by peer”
- r - 嵌套的 For 循环函数目标未完成
- angular - 登录 - Grafana 与 Angular+SpringBoot
- html - 使用 xmlstarlet 编辑 HTML 中特定节点的 XPath 语法
- javascript - 我可以从不可见的组件中获取事件吗?(Vue.js)
- amazon-web-services - 如何获取和显示一组网络图像?
- angular - 从 Angular v7 升级到 v8 后,显示“my-custom-element”的 VS 代码不是已知元素
- swiftui - 是否可以指示 swiftUI ObservableObjects 在数据更改事件时修改自己?
- javascript - 用 Javascript 重写 Fetch API