簡體   English   中英

將計算值分配給 function R 中的 object

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

我正在嘗試使用 function 為所有特征返回一個 object,其值為“alt_props”。 (alt_props xb) 至少應為 30,因此當計算出的 (alt_props xb) 低於 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] <- 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)

第二次嘗試這個答案。 通過使用colSumsstb應該都是相同長度的向量,您計算比例並將其存儲在向量alt_props中。 現在,如果條件(alt_props * b) < 30 ,您要輸入值30/b 我們可以嘗試使用值和條件向量來做到這一點。 請參閱新的 function。 我看不到原始 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