Paolo Lorenzini
Paolo Lorenzini

Reputation: 725

R functions looping

Hi I have a data frame df with 3 columns as follows:

 a    b    c
-2    A    G
 1    G    C
 3    T    C
-4    A    G

I would like to create a new column d which takes the value in b if the value in a is negative while it takes the value of c if positive:

 a     b     c    d
-2     A     G    A
 1     G     C    C
 3     T     C    C
-4     A     G    A

I wrote something a function like this but it is not working

select_allele<-function(x,y){ 
  for(i in 1:nrow(df)){   
    if(df$a[i] > 0){
      df$d[i] <- return(y)   
    } else {
      df$d[i] <- return(x)   
    } 
}} 

mapply(select_allele, x=df$b, y=df$c)

Any help highly appreciated.

Upvotes: 3

Views: 56

Answers (2)

tushaR
tushaR

Reputation: 3116

Assuming that while creating df you set the stringsAsFactors = FALSE in data.frame().

df$d <-ifelse(df$a>0,df$c,df$b)

#   a b c d
#1 -2 A G A
#2  1 G C C
#3  3 T C C
#4 -4 A G A

Upvotes: 3

Ronak Shah
Ronak Shah

Reputation: 388817

There are multiple ways to do this. One way using sign function which returns the sign of a number

df$d <- with(df, ifelse(sign(a) == -1, b, c))
df

#   a b c d
#1 -2 A G A
#2  1 G C C
#3  3 T C C
#4 -4 A G A

Or with dplyr if_else

library(dplyr)
df %>% mutate(d = if_else(a < 0, b, c))

data

df <- structure(list(a = c(-2L, 1L, 3L, -4L), b = c("A", "G", "T", 
"A"), c = c("G", "C", "C", "G")), .Names = c("a", "b", "c"), row.names = c(NA, 
-4L), class = "data.frame")

Upvotes: 4

Related Questions