r - 跟进:将给定的缺失列从 data.frame 放回 dta.frames 列表
问题描述
我正在跟进这个问题。下面我LIST
的 data.frames 是由我的data
. 但是,这LIST
缺少原始中可用的列(始终提供缺少的列的名称paper
)。data
我想知道如何将丢失的paper
列放回LIST
以实现我的DESIRED_LIST
以下?
我尝试了这个答案( lapply(LIST, function(x)data[do.call(paste, data[names(x)]) %in% do.call(paste, x),])
) 中建议的解决方案,但它没有产生我的DESIRED_LIST
.
赞赏 Base R 或 tidyverse 解决方案。
可重现的数据和代码如下。
m2="
paper study sample comp ES bar
1 1 1 1 1 7
1 2 2 2 2 6
1 2 3 3 3 5
2 3 4 4 4 4
2 3 4 4 5 3
2 3 4 5 6 2
2 3 4 5 7 1"
data <- read.table(text=m2,h=T)
LIST <- list(data.frame(study=1 ,sample=1 ,comp=1),
data.frame(study=rep(3,4),sample=rep(4,4),comp=c(4,4,5,5)),
data.frame(study=c(2,2) ,sample=c(2,3) ,comp=c(2,3)))
DESIRED_LIST <- list(data.frame(paper=1 ,study=1 ,sample=1 ,comp=1),
data.frame(paper=rep(2,4),study=rep(3,4),sample=rep(4,4),comp=c(4,4,5,5)),
data.frame(paper=rep(1,2),study=c(2,2) ,sample=c(2,3) ,comp=c(2,3)))
解决方案
- 请使用包找到解决方案
data.table
。这是你要找的吗?
代表 1
library(data.table)
cols_to_remove <- c("ES")
split(setDT(data)[, (cols_to_remove) := NULL], by = c("paper", "study"))
#> $`1.1`
#> paper study sample comp
#> 1: 1 1 1 1
#>
#> $`1.2`
#> paper study sample comp
#> 1: 1 2 2 2
#> 2: 1 2 3 3
#>
#> $`2.3`
#> paper study sample comp
#> 1: 2 3 4 4
#> 2: 2 3 4 4
#> 3: 2 3 4 5
#> 4: 2 3 4 5
由reprex 包于 2021-11-06 创建(v2.0.1)
编辑
- 请在包中找到解决方案 2
dplyr
代表 2
library(dplyr)
drop.cols <- c("ES")
data %>%
group_by(paper, study) %>%
select(-drop.cols) %>%
group_split()
#> <list_of<
#> tbl_df<
#> paper : integer
#> study : integer
#> sample: integer
#> comp : integer
#> >
#> >[3]>
#> [[1]]
#> # A tibble: 1 x 4
#> paper study sample comp
#> <int> <int> <int> <int>
#> 1 1 1 1 1
#>
#> [[2]]
#> # A tibble: 2 x 4
#> paper study sample comp
#> <int> <int> <int> <int>
#> 1 1 2 2 2
#> 2 1 2 3 3
#>
#> [[3]]
#> # A tibble: 4 x 4
#> paper study sample comp
#> <int> <int> <int> <int>
#> 1 2 3 4 4
#> 2 2 3 4 4
#> 3 2 3 4 5
#> 4 2 3 4 5
由reprex 包于 2021-11-07 创建(v2.0.1)
推荐阅读
- ansible - Ansible URI 模块从变量传递整数
- .net - PyQt5 剪贴板不适用于 clr
- reactjs - 让孩子改变父母的状态,这是一个数组
- node.js - 使用 NodeJs 从管道远程流中提取单个文件到 unzip.Parse() 而不读取整个流
- django - Django - NOT NULL 约束失败和 WSGIRequest 错误
- sml - 为什么这会导致溢出错误?(SML)
- r - 为 R 中不存在的值设置级别
- python - Python:stockstats 期望的数据结构是什么?
- rx-java - 订阅 observable 时如何保证 GC
- linux-kernel - 强制 copy_to_user() 失败