Ifelse statement with variable output variable

I have a dataframe df

  SNP           Effect   A1 A2
8  rs12145743    -0.0203  T  G
31  rs4650994    -0.0210  A  G
26  rs2602836     0.0192  A  G
34  rs4976033     0.0215  A  G
10 rs12525163    -0.0215  T  C
1  rs10282707    -0.0250  T  C
33  rs4917014    -0.0222  T  G
23  rs2293889    -0.0312  T  G
32  rs4871137    -0.0209  T  G
43   rs970548    -0.0258  A  C
27  rs2923084     0.0256  A  G
24  rs2303975     0.0279  A  G
36   rs499974    -0.0263  A  C
35  rs4983559    -0.0197  A  G
13 rs16942887     0.0831  A  G
16 rs17695224    -0.0290  A  G
18   rs181362    -0.0379  T  C

      

I am creating a new variable new_A1

which will differ depending on the value Effect

.

If Effect

> 0, new_A1

must contain a value A1

.

If Effect

<0, new_A1

must contain a value A2

.

I am trying to do this using the following ifelse statement:

df$new_A1 <- ifelse(df$Effect>0, df$A1, df$A2)

      

However, the output is not as expected. new_A1

contains 1s and 2s instead of storing the values โ€‹โ€‹of the factors in the original variables A1

andA2

  SNP           Effect   A1 A2 new_a1
8  rs12145743    -0.0203  T  G      2
31  rs4650994    -0.0210  A  G      2
26  rs2602836     0.0192  A  G      1
34  rs4976033     0.0215  A  G      1
10 rs12525163    -0.0215  T  C      1
1  rs10282707    -0.0250  T  C      1
33  rs4917014    -0.0222  T  G      2
23  rs2293889    -0.0312  T  G      2
32  rs4871137    -0.0209  T  G      2
43   rs970548    -0.0258  A  C      1
27  rs2923084     0.0256  A  G      1
24  rs2303975     0.0279  A  G      1
36   rs499974    -0.0263  A  C      1
35  rs4983559    -0.0197  A  G      2
13 rs16942887     0.0831  A  G      1
16 rs17695224    -0.0290  A  G      2
18   rs181362    -0.0379  T  C      1

      

+3


source to share


2 answers


The processing of variable factors A1

and A2

, since symbolic variables give the appropriate result.



hdl.dir$new_A1 <- ifelse(hdl.dir$HDL_Effect<0, as.character(hdl.dir$A2), as.character(hdl.dir$new_A1))

+1


source


You can try index row / col. This should work even without converting the explicit "factor" to the "character" class.



 df$new_a1 <- df[3:4][cbind(1:nrow(df),(df$Effect<=0)+1L)]

      

+1


source







All Articles