Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
351 views
in Technique[技术] by (71.8m points)

if statement - Conditional assignment of variable to dataframe in R

My data frame

 A tibble: 6 x 3
  ENSEMBL           RNA   ATAC
  <chr>           <dbl>  <dbl>
1 ENSG00000230368 -2.97 -3.33 
2 ENSG00000067606 -2.37  5.08 
3 ENSG00000078900  1.99 -0.721
4 ENSG00000235169 -1.74 -1.75 
5 ENSG00000116254  2.03 -0.156
6 ENSG00000173662  3.68 -4.00 

dput(head(dat))
structure(list(ENSEMBL = c("ENSG00000230368", "ENSG00000067606", 
"ENSG00000078900", "ENSG00000235169", "ENSG00000116254", "ENSG00000173662"
), RNA = c(-2.97191791457744, -2.37449980658652, 1.99184229821186, 
-1.74292940411696, 2.03328766113218, 3.68062522542837), ATAC = c(-3.3250605, 
5.0795755229987, -0.720667666666667, -1.74733, -0.155942, -4.004811
)), row.names = c(NA, -6L), class = c("tbl_df", "tbl", "data.frame"
))

My objective is to see if both the column are negative then I would assign a string "UP" and if both the columns are positive and then string "DOWN" if both the columns are negative. So to do this Im doing the following.

dat[4] <- data.frame(AB = dat$RNA*dat$ATAC) # creating another column where Im taking the product of both RNA and ATAC column.

The this

dat[4] <- ifelse(dat[, 4] > 0, "UP", "DOWN")

which gives me this

    ENSEMBL           RNA   ATAC AB   
  <chr>           <dbl>  <dbl> <chr>
1 ENSG00000230368 -2.97 -3.33  UP   
2 ENSG00000067606 -2.37  5.08  DOWN 
3 ENSG00000078900  1.99 -0.721 DOWN 
4 ENSG00000235169 -1.74 -1.75  UP   
5 ENSG00000116254  2.03 -0.156 DOWN 
6 ENSG00000173662  3.68 -4.00  DOWN 

The issue is here is row number 4 both are negative but i still see "UP" . This was supposed to be "DOWN but as both the negative would give a product which would be positive so it goes "UP" I think

How to resolve the issue ? where i would see if both the column negative then the 4th column should be "DOWN" and if both RNA and ATAC column are positive then I would see "UP" in the 4th column.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What if one is positive and other is negative? The below answer assigns NA to it.

library(dplyr)
dat %>%
  mutate(AB = case_when(RNA < 0 & ATAC < 0 ~ 'Down', 
                        RNA > 0 & ATAC > 0 ~ 'Up'))

You can also use sign where 1 is positive, -1 is negative and 0 is for 0 value.

transform(dat, AB = ifelse(sign(RNA) == -1 & sign(ATAC) == -1, 'Down', 
                         ifelse(sign(RNA) == 1 & sign(ATAC) == 1, 'Up', NA)))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...