后续行动:将data.frame中给定的缺失列放回dta.frame列表中 [英] Follow-up: Putting back a given missing column from a data.frame into a list of dta.frames

查看:23
本文介绍了后续行动:将data.frame中给定的缺失列放回dta.frame列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在跟进this question。下面的LIST个数据帧由我的data组成。但是,此LIST缺少原始data中提供的paper列(始终提供缺少的列的名称)。

我想知道如何将缺少的paper列放回LIST中以实现下面的DESIRED_LIST

我尝试了this answer(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的解决方案。这就是您要找的东西吗?

Reprex%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 package(v2.0.1)于2021-11-06创建


编辑

  • 请使用包dplyr
  • 查找解决方案2

Reprex 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 package(v2.0.1)于2021-11-07创建

这篇关于后续行动:将data.frame中给定的缺失列放回dta.frame列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆