将向量列表中的每个相似命名的元素提交给R中的函数 [英] Submit every similarly named elements of a list of vectors to a function in R

查看:114
本文介绍了将向量列表中的每个相似命名的元素提交给R中的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下,我想知道如何分别使用 L <中的 across 元素中的 across 元素来使用BASE R函数 quantile() / code>分别命名为 EFL ESL

Below, I'm wondering how to use BASE R function quantile() separately across elements in L that are named EFL and ESL?

注意:这是一个玩具示例, L 可以包含任意数量的相似命名的元素。

Note: this is a toy example, L could contain any number of similarly named elements.

foo <- function(X) {
  X <- as.matrix(X)
  tab <- table(row(X), factor(X, levels = sort(unique(as.vector(X)))))
  w <- diag(ncol(tab))
  rosum <- rowSums(tab)
  obs_oc <- tab * (t(w %*% t(tab)) - 1)
  obs_c <- colSums(obs_oc)
  max_oc <- tab * (rosum - 1)
  max_c <- colSums(max_oc)
  SA <- obs_c / max_c
  h <- names(SA)
  h[is.na(h)] <- "NA"
  setNames(SA, h)
}  

DAT <- read.csv("https://raw.githubusercontent.com/rnorouzian/m/master/X.csv", row.names = 1)
L <- replicate(50, foo(DAT[sample(1:nrow(DAT), replace = TRUE),]), simplify = FALSE)

# How to use `quantile()` separately across all similarly named elements (e.g., EFL, ESL) in `L[[i]]` i = 1,... 5

# quantile(all EFL elements across `L`)
# quantile(all ESL elements across `L`)


推荐答案

我以前使用的解决方案 do.call rbind 将每个列表放入矩阵和数组,然后计算每个data.frame行的分位数。

The previous solution I used do.call to rbind each list into a matrix and array and then calculate the quantile over each data.frame row.

sapply(as.data.frame(do.call(rbind, L)), quantile)

但是,当缺少行时,不需要考虑到这一点。为了准确地获取行,您需要填充缺少的行。我使用了 data.table rbindlist (也可以使用 plyr :: rbind。用 fill = TRUE 填充)来填充缺少的值。它要求每个都必须是一个data.frame / table / list,所以我将每个都转换为一个data.frame,但是在这样做之前,您需要转置( t())数据,以便行与每个元素对齐。它可以单行编写,但更容易读取多行中发生的事情。

However, when there is a missing row, it does not take that into account. To accurately get the rows you need to fill the missing rows. I used data.table's rbindlist (you could also use plyr::rbind.fill) with fill=TRUE to fill the missing values. It requires each to be a data.frame/table/list, so I converted each to a data.frame, but before doing so you need to transpose (t()) the data so that the rows line up to each element. It could be written in a single line, but it's easier read what is happening in multiple lines.

L2 = lapply(L, function(x){as.data.frame(t(x))})
df = data.table::rbindlist(L2, fill=TRUE) # or plyr::rbind.fill(L2)
sapply(df, quantile, na.rm = TRUE)

这篇关于将向量列表中的每个相似命名的元素提交给R中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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