r - Multiple if statement to change sign of column values -


i try change positive/negative sign of column values based on multiple conditions. dataframe looks this:

df rs     pub_snp   snp    b rs_1    g         g     0.1 rs_2    c            -0.2 rs_3            t     0.3 rs_4    t         c    -0.4 rs_5    t         g     0.5 

based on df$pub_snp , df$snp im trying change column df$b,

(please notice, code not work, represent im trying 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) 

i following output:

df     rs     pub_snp   snp    b     newb     rs_1    g         g     0.1   0.1     rs_2    c            -0.2   0.2     rs_3            t     0.3   0.3     rs_4    t         c    -0.4   0.4     rs_5    t         g     0.5  -0.5 

thank , suggestions.

try this:

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 

Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

java - Digest auth with Spring Security using javaconfig -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -