【问题标题】:R: iterate a function over two lists simultaneously using lapply?R:使用 lapply 同时在两个列表上迭代一个函数?
【发布时间】:2018-05-08 00:10:31
【问题描述】:

我有多个因素来划分我的数据。

通过一个因素 (uniqueGroup),我想对我的数据进行子集化,通过另一个因素 (distance),我想首先通过“移动阈值”对我的数据进行分类,然后测试组之间的统计差异。

我创建了一个函数movThreshold 来对我的数据进行分类,并通过wilcox.test 对其进行测试。要改变不同的阈值,我只需运行

lapply(th.list,       # list of thresholds
       movThreshold,  # my function
       tab = tab,     # original data
       dependent = "infGrad") # dependent variable

现在我意识到,实际上我需要先将我的数据子集通过uniqueGroup,然后然后改变阈值。但我不确定,如何在我的lapply 代码中编写它?


我的虚拟数据:

set.seed(10)
infGrad <- c(rnorm(20, mean=14, sd=8),
            rnorm(20, mean=13, sd=5),
            rnorm(20, mean=8, sd=2),
            rnorm(20, mean=7, sd=1))
distance <- rep(c(1:4), each = 20)
uniqueGroup <- rep(c("x", "y"), 40)

tab<-data.frame(infGrad, distance, uniqueGroup)


# Create moving threshold function &
# test for original data
# ============================================

movThreshold <- function(th, tab, dependent, ...) {

  # Classify data 
  tab$group<- ifelse(tab$distance < th, "a", "b")

  # Calculate wincoxon test - as I have only two groups
  test<-wilcox.test(tab[[dependent]] ~ as.factor(group),  # specify column name
                    data = tab)

  # Put results in a vector 
  c(th, unique(tab$uniqueGroup), dependent, uniqueGroup, round(test$p.value, 3))

}

# Define two vectors to run through
# unique group
gr.list<-unique(tab$uniqueGroup)

# unique threshold
th.list<-c(2,3,4)

如何在两个列表上运行lapply??

lapply(c(th.list,gr.list),  # iterate over two vectors, DOES not work!!
              movThreshold, 
              tab = tab, 
              dependent = "infGrad")

在我之前的问题 (Kruskal-Wallis test: create lapply function to subset data.frame?) 中,我学习了如何遍历表中的各个子集:

lapply(split(tab, df$uniqueGroup), movThreshold})

但是如何遍历子集并同时通过阈值?

【问题讨论】:

    标签: r lapply literate-programming


    【解决方案1】:

    如果我正确理解了您要执行的操作,这是data.table 解决方案:

    library(data.table)
    setDT(tab)[, lapply(th.list, movThreshold, tab = tab, dependent = "infGrad"), by = uniqueGroup]
    

    另外,你可以只做一个嵌套的lapply

    lapply(gr.list, function(z) lapply(th.list, movThreshold, tab = tab[uniqueGroup == z, ], dependent = "infGrad"))
    

    如果我误解了您的意图,我深表歉意。

    【讨论】:

    • 酷,谢谢@YannisVassiliadis!只有一个错字:我认为 'tab = tab[uniqueGroup == x]' 在 x 之后应该有一个逗号,'i.e. tab = tab[uniqueGroup == x,]',否则效果很好:-D
    猜你喜欢
    • 2021-04-29
    • 2020-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多