多个if语句来更改列值的符号

时间:2016-05-28 11:22:51

标签: r

我尝试根据多个条件更改列值的正/负符号。我的数据框看起来像这样:

<?php

namespace App\Events\Frontend\Auth;

use App\Events\Event;
use Illuminate\Queue\SerializesModels;

/**
 * Class UserRegistered
 * @package App\Events\Frontend\Auth
 */
class UserRegistered extends Event
{
    use SerializesModels;

    /**
     * @var $user
     */
    public $user;

    /**
     * @param $user
     */
    public function __construct($user)
    {
        $this->user = $user;
    }
}

基于DF RS Pub_SNP SNP B rs_1 G G 0.1 rs_2 C A -0.2 rs_3 A T 0.3 rs_4 T C -0.4 rs_5 T G 0.5 DF$Pub_SNP我试图更改列DF$SNP,以便

DF$B

我想得到以下输出:

(please notice, code does not work, so just represent what im trying to achive)
DF$new_B <- ifelse(DF$pub_SNP=="C" & DF$SNP=="G" &
                   DF$pub_SNP=="C" & DF$SNP=="C" &
                   DF$pub_SNP=="G" & DF$SNP=="G", 
                   DF$B, DF$B) 
DF$new_B<- ifelse(DF$pub_SNP=="A" & DF$SNP=="T" &
                     DF$pub_SNP=="A" & DF$SNP=="A" &
                     DF$pub_SNP=="T" & DF$SNP=="T", 
                     DF$B,DF$B)

感谢您提供任何帮助和建议。

2 个答案:

答案 0 :(得分:1)

试试这个:

S <- c("C", "G")
W <- c("A", "T")

new.b <- function(data){
    s1 <- data[2]
    s2 <- data[3]
    b <- as.numeric(data[4])
    sw <- ifelse(sum(s1 %in% S, s2 %in% S) == 2 | sum(s1 %in% W, s2 %in% W) == 2, 1, -1)
    return(b*sw)
}

df$newB <- apply(df, 1, new.b)
# [1]  0.1  0.2  0.3  0.4 -0.5

答案 1 :(得分:0)

自您尝试以来,只是抛出了正确的ifelse方法,

ifelse(DF$pub_SNP=="C" & DF$SNP=="G" |
                        DF$pub_SNP=="C" & DF$SNP=="C"|
                        DF$pub_SNP=="G" & DF$SNP=="G"| 
                        DF$pub_SNP=="A" & DF$SNP=="T" |
                        DF$pub_SNP=="A" & DF$SNP=="A" |
                        DF$pub_SNP=="T" & DF$SNP=="T", DF$B, -1*DF$B)

#[1]  0.1  0.2  0.3  0.4 -0.5