【问题标题】:Assign a calculated value to an object in a function R将计算值分配给函数 R 中的对象
【发布时间】:2020-08-21 04:06:33
【问题描述】:

我正在尝试使用函数为所有特征返回一个值为“alt_props”的对象。 (alt_props x b) 至少应为 30,因此当计算出的 (alt_props x b) 低于 30 时,该 alt_props 值应更改为 alt_props 值 30/b。 (1:7) 是代表不同特征的列。

calc_props <- function(x, pvals, betas){
  s <- colSums(pvals < 5e-8, na.rm = TRUE) #significant SNPs
  t <- colSums(!is.na(pvals)) #all SNPs
  b <- colSums(!is.na(betas)) #Number of betas 
  alt_props <- s/t    #alt_prop calculation
  a[x] <- 30/b #value to assign if alt_props*b < 30
  alt_props[(alt_props*b) < 30] <- a[x] #check to ensure that "alt_prop*b" is atleast 30
  alt_props
}

alt_props <- calc_props(1:7, pvals, betas) #the columns are the traits (7)

但是,在运行此代码时,我收到错误 Error in a[x] &lt;- 30/b : object 'a' not found。我怎样才能分配正确的a?

我的数据如下所示:

dput(pvals[1:10])
c(0.14, 0.87, 3.7e-23, 1.2e-07, 0.84, 0.72, 0.34, 0.13, 0.019, 
8e-05)
> dput(betas[1:10])
c(-0.0021, 2e-04, -0.0141, -0.0082, -7e-04, 8e-04, 0.0021, -0.0034, 
-0.0039, 0.0179)

【问题讨论】:

  • 这正是错误所说的:a 不存在。 a 没有在函数内部或外部定义,我想。您正在尝试索引在搜索路径中找不到的对象 aa 应该是什么?同样在未来,请提供一些示例数据和可重复的示例,包括您期望的结果。这将使人们更容易为您提供帮助。
  • @edsandorf 我以后会牢记这一点。 a 应该是一个临时值,当计算出的alt_props 值不满足条件(即alt_props*b should be &gt; 30)时,可以分配给alt_props 值。当不满足条件时,alt_props 应更改为导致 alt_props * b) 为 30 的值 --> 这应该是 a
  • 对可重现示例的建议:stackoverflow.com/questions/5963269/…

标签: r function return assign


【解决方案1】:

第二次尝试这个答案。通过使用colSumsstb 来判断应该都是相同长度的向量,然后计算比例并将其存储在向量alt_props 中。现在,如果条件为(alt_props * b) &lt; 30,则要输入值30/b。我们可以尝试使用值和条件向量来做到这一点。查看新功能。我看不到原始函数中需要x,因为它似乎只用于以某种方式对a 进行子集化。

calc_props <- function(x, pvals, betas){
  s <- colSums(pvals < 5e-8, na.rm = TRUE)
  t <- colSums(!is.na(pvals)) #all SNPs
  b <- colSums(!is.na(betas)) #Number of betas 
  alt_props <- s/t    #alt_prop calculation

  # Create the subsetting values and condition
  condition_val <- 30/b
  condition <- (alt_props*b) < 30

  # Subset both the alt_props and condition values with the same vector
  alt_props[condition] <- condition_val[condition] 
  alt_props
}

【讨论】:

  • Warning message: In alt_props[(alt_props * b) &lt; 30] &lt;- 30/b : number of items to replace is not a multiple of replacement length。不幸的是,我在使用向量时也遇到了同样的错误
  • 我已将 pvals 和 betas 数据添加到我的问题中。现在可以重现了吗?
  • 不是。 pvalsbetas 是矩阵,你提供了向量。我第二次尝试解决方案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-22
  • 1970-01-01
  • 1970-01-01
  • 2016-01-15
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
相关资源
最近更新 更多