簡體   English   中英

根據對三列 R 的數學計算將值添加到新列

[英]Add values to a new column based on math calculations on three columns R

我有一個如下結構的數據框:

head(test)

   geneA  geneB start end position
1  Ypc1 Malat1    34  59       36
2  Ypc1 Malat1    35  60       26
3  Ypc1 Malat1    34  59       60

我想在startendposition三個列上添加一個名為distance的新列,該列基於條件數學運算。 我使用了下面的 if 語句,但distance列總是為0 在 if 語句之后,我的 output 看起來像這樣:

if (test$position < test$start) {
  test$distance <- test$start - test$position
} else if (test$position >= test$start & test$position <= test$end) {
  test$distance <- 0
} else if (test$position > test$end) {
  test$distance <- test$end - test$position
}

head(test)
   geneA  geneB start end position distance
1  Ypc1 Malat1    34  59       36        0
2  Ypc1 Malat1    35  60       26        0
3  Ypc1 Malat1    34  59       60        0

所需的 output 應該是:

   geneA  geneB start end position distance
1  Ypc1 Malat1    34  59       36        0
2  Ypc1 Malat1    35  60       26        9
3  Ypc1 Malat1    34  59       60        -1

我怎樣才能做到這一點?

先感謝您。

沿向量測試條件時,應使用ifelse 我在下面更正了您的代碼:

test <- data.frame(geneA = c("Ypc1"), geneB = c("Malat1"),
                   start = c(34, 35, 34),
                   end = c(59, 60, 59),
                   position = c(36, 26, 60))

test$distance <- ifelse(
    test$position < test$start,
    test$distance <- test$start - test$position, 
    ifelse(
        test$position >= test$start & test$position <= test$end,
        test$distance <- 0,
        test$distance <- test$end - test$position
    ))
test
# geneA  geneB start end position distance
# 1  Ypc1 Malat1    34  59       36        0
# 2  Ypc1 Malat1    35  60       26        9
# 3  Ypc1 Malat1    34  59       60       -1

但是這不是很不穩定,我會尋找一種更短的方法來計算它!

我還嘗試使用awk

awk -F, '{if($3<$1);
          print $1,$2,$3,$1-$3; 
          else if($3>$2);
          print $1,$2,$3,$2-$3; 
          else print $1,$2,$3,0}'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM