简体   繁体   中英

warning with if else statement in R

My data looks similar to this

start end strand
45    52    +
66    99    -

Lets call this table1 .

If I have a + in strand , I have to return two values , which are +/- 10 from start value.

So, here I have to return 55 and 35.

If I have a - in strand , I have to return two values , which are +/- 10 from end value.

To do this , I wrote this program:

if(table1$strand == '+'){
newstart = table1$start - 10
newend = table1$start + 10
} else {
newstart = table1$end - 10
newend = table1$end + 10
}

But, I get this warning message:

the condition has length > 1 and only the first element will be used

Is there a way using vectorized methods, to avoid this?

You want to use ifelse to vectorize the process:

ifelse(table1$strand == '+', table1$start, table1$end) 

This does everything in one step:

> outer(ifelse(table1$strand == '+', table1$start, table1$end), c(10, -10), `+`)
     [,1] [,2]
[1,]   55   35
[2,]  109   89

Here's an example using ifelse . If this is your sample data

table1<-structure(list(start = c(45L, 66L), end = c(52L, 99L), strand = structure(c(2L, 
1L), .Label = c("-", "+"), class = "factor")), .Names = c("start", 
"end", "strand"), class = "data.frame", row.names = c(NA, -2L))

then you could do

newstart <- ifelse(table1$strand=="+", table1$start, table1$end)-10
newend <- newstart + 20

to operate on all rows at once.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM