后续:从BASE R中的两个列表中提取一个data.frame [英] Follow-up: Extracting a data.frame from two lists in BASE R

查看:26
本文介绍了后续:从BASE R中的两个列表中提取一个data.frame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在跟踪答案.答案的输出效果很好(请参见下文):

I'm following up on this answer. The output in that answer works great (see below):

             tlist.mpre tlist.sdpre tlist.n clist.mpre clist.sdpre clist.n
Dlsk_Krlr.102       81.6        10.8      73       80.5        11.2      80
Dlsk_Krlr.103       85.7        13.7      66       90.3         6.6      74
Dlsk_Krlr.104       81.4        10.9      72       80.5        11.2      80
Dlsk_Krlr.105       90.4         8.2      61       90.3         6.6      74

但是,我想从 data 提取并添加两个名为 nms = c('time_wk','treats')的列到上述输出中.但是,当我向其中添加 nms 时,新的输出(请参见下面的R代码的末尾)会变得混乱.

However, I want to extract and add two columns named nms = c('time_wk','treats') from data to the above output. But the new output (see end of R code below) gets scrambled when I add nms to it.

鉴于我下面的可复制R代码是否有修复程序?

Given my reproducible R code below is there a fix?

data <- read.csv("https://raw.githubusercontent.com/rnorouzian/m2/main/q.csv")

nms = c('time_wk','treats')

m = split(data, data$study.name)

(mm = m["Dlsk_Krlr"])


(input <- lapply(mm, function(i) 
  rev(expand.grid(post = unique(i$post),outcome = unique(i$outcome)))))

res <- setNames(lapply(1:0, function(i) lapply(input, function(inp) Map(function(o, p)
  do.call(rbind, lapply(mm, function(x)
    x[x$control == i & x$post == p & x$outcome == o, , drop = FALSE])),
  inp$outcome, inp$post))), c("clist", "tlist"))


(aa = setNames(lapply(seq_along(res), function(i) Filter(NROW, res[[i]][[1]])), names(res)))


b <- lapply(aa, function(x)  {
  y <- do.call(rbind,  x);
  y[order(y$group), c("mpre", "sdpre", "n", nms)] }) ## I'm adding `nms` HERE but that scrambles the output below

cc = do.call(cbind,rev(b))
cc_1 = cc[!duplicated(cc),]
names(cc_1)[1:6] = c('mT','sdT','nT','mC','sdC','nC')

### NEW SCRAMBLED OUTPUT AFTER ADDING `nms`:
#                mT  sdT nT mC sdC   nC clist.sdpre clist.n clist.time_wk clist.treats
#Dlsk_Krlr.102 81.6 10.8 73  1   2 80.5        11.2      80             1            2
#Dlsk_Krlr.103 85.7 13.7 66  1   2 90.3         6.6      74             1            2
#Dlsk_Krlr.104 81.4 10.9 72  1   2 80.5        11.2      80             1            2
#Dlsk_Krlr.105 90.4  8.2 61  1   2 90.3         6.6      74             1            2

推荐答案

这是基本的R解决方案:

Here is the base R solution:

cc[,grep(sprintf("clist.(%s)", paste0(nms, collapse="|")), names(cc), invert = TRUE)]

确保nms到达最后一个:

to ensure the nms comes the last:

d<-cc[grep(sprintf("clist.(%s)", paste0(nms, collapse="|")), names(cc), invert = TRUE)]

i1 <- grepl(sprintf("(%s)", paste0(nms, collapse="|")), names(d))

cbind(d[!i1], d[i1])

这篇关于后续:从BASE R中的两个列表中提取一个data.frame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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