简体   繁体   English

在R中使用if else语句警告

[英]warning with if else statement in R

My data looks similar to this 我的数据看起来与此相似

start end strand
45    52    +
66    99    -

Lets call this table1 . 让我们将此表称为1。

If I have a + in strand , I have to return two values , which are +/- 10 from start value. 如果我有一个+链,我必须返回两个值,它们是起始值的+/- 10。

So, here I have to return 55 and 35. 因此,在这里我必须返回55和35。

If I have a - in strand , I have to return two values , which are +/- 10 from end value. 如果我有一个-in链,则必须返回两个值,它们是最终值的+/- 10。

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 条件的长度> 1,并且仅使用第一个元素

Is there a way using vectorized methods, to avoid this? 有没有一种使用矢量化方法的方法来避免这种情况?

You want to use ifelse to vectorize the process: 您要使用ifelse来矢量化该过程:

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 . 这是使用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. 一次对所有行进行操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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