繁体   English   中英

在R中使用if else语句警告

[英]warning with if else statement in R

我的数据看起来与此相似

start end strand
45    52    +
66    99    -

让我们将此表称为1。

如果我有一个+链,我必须返回两个值,它们是起始值的+/- 10。

因此,在这里我必须返回55和35。

如果我有一个-in链,则必须返回两个值,它们是最终值的+/- 10。

为此,我编写了以下程序:

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

但是,我收到此警告消息:

条件的长度> 1,并且仅使用第一个元素

有没有一种使用矢量化方法的方法来避免这种情况?

您要使用ifelse来矢量化该过程:

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

这一步完成了所有操作:

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

这是使用ifelse的示例。 如果这是您的样本数据

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))

那你可以做

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

一次对所有行进行操作。

暂无
暂无

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

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