简体   繁体   English

将计算值分配给 function R 中的 object

[英]Assign a calculated value to an object in a function R

I'm trying to return an object with a value 'alt_props' for all traits with the use of a function.我正在尝试使用 function 为所有特征返回一个 object,其值为“alt_props”。 (alt_props xb) should at least be 30, so when the calculated (alt_props xb) is lower than 30, that alt_props value should be changed to the alt_props value of 30/b. (alt_props xb) 至少应为 30,因此当计算出的 (alt_props xb) 低于 30 时,应将 alt_props 值更改为 alt_props 值 30/b。 (1:7) are the columns that represent the different traits. (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)

However, when running this code I get the error Error in a[x] <- 30/b: object 'a' not found .但是,在运行此代码时,我收到错误Error in a[x] <- 30/b: object 'a' not found How can i assign the correct a?我怎样才能分配正确的a?

My data looks like this:我的数据如下所示:

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)

Second attempt at this answer.第二次尝试这个答案。 Juding by the use of colSums , s , t and b should all be vectors of the same length, and you calculate the proportions and store that in the vector alt_props .通过使用colSumsstb应该都是相同长度的向量,您计算比例并将其存储在向量alt_props中。 Now, you want to input the value 30/b if the condition (alt_props * b) < 30 .现在,如果条件(alt_props * b) < 30 ,您要输入值30/b We can try to do this using a value and condition vector.我们可以尝试使用值和条件向量来做到这一点。 See the new function.请参阅新的 function。 I couldn't see the need for the x in the original function since it appeared to only be used to subset a somehow.我看不到原始 function 中对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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM