后续操作:将data.frame中缺少的列重新放回dta.frame列表中 [英] Follow-up: Putting back a missing column from a data.frame into a list of dta.frames

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

问题描述

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

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

我尝试了this question(lapply(LITS,function(x)merge(x,data)[names(data)]))中建议的解决方案,但未生成DESIRED_LIST

可复制的数据和代码如下。

m2="
paper     study sample    comp
1         1     1         1
1         2     2         2
1         2     3         3
2         3     4         4
2         3     4         4
2         3     4         5
2         3     4         5"
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)))

推荐答案

一个选项是循环list(‘List’),根据pasteed数据行和列表元素数据

设置data基于%in%data子集
LIST2 <-  lapply(LIST, function(x) 
    data[do.call(paste, data[names(x)]) %in% do.call(paste, x),])

-正在检查

> all.equal(DESIRED_LIST, LIST2, check.attributes = FALSE)
[1] TRUE

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

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