首页 > 解决方案 > 跟进:将给定的缺失列从 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)))

标签: rlistdataframedplyrtidyverse

解决方案


  • 请使用包找到解决方案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)


编辑

  • 请在包中找到解决方案 2dplyr

代表 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)


推荐阅读