嵌套多个if-else

时间:2017-05-16 11:33:02

标签: r if-statement dataframe

我试图用R中的嵌套if-else编写一个函数。如何转换data.frame,其中列的值设置为:

输入

nil

预期产出

 df <- read.table(header = TRUE, text="Chr     start       end        num    seg.mean    seg.mean.1   seg.mean.2
    1   68580000    68640000    A8430    0.7000      0     0.1032 
    1   115900000   116260000   B8430    0.0039      2.7202     2.7202
    1   173500000   173680000   C5      -1.7738      -2.0746    -0.2722")

condition:  
     x > 0 & x< 1      : 1
     x >= 1            : 2
     x < 0 & x > - 1   : -1
     x <= -1           : -2
     x = 0             : 0

2 个答案:

答案 0 :(得分:1)

我认为你想要的是:

x == 0

尝试一下......

  

请注意,-2x <= 0 ...。没有您所描述的x >= 0 ...0表达式。

如果您希望x = c(-1,1,0,0,1,-1,0.5,0.3, -0.4) fun_cond(x) fun_cond <- function(x){ ifelse(x >= 1, 2, ifelse(x < 1 & x > 0, 1, ifelse( x == 0, 0, ifelse(x < 0 & x > -1, -1, -2)))) } > fun_cond(x) #[1] -2 2 0 0 2 -2 1 1 -1 为零,请使用:

java.time.LocalTime

答案 1 :(得分:1)

在基地R中尝试cut

cols <- grep("seg.mean", names(df))
res <- sapply(cols, function(i) 
                     cut(df[,i], breaks = c(-Inf, -1, 0, 1, Inf), labels = c(-2,-1,1,2)))

# to leave zeros untouched
res[df[cols]==0] <- 0

如果您想获得预期的输出:

df[cols] <- res

  # Chr     start       end   num seg.mean seg.mean.1 seg.mean.2
# 1   1  68580000  68640000 A8430        1          0          1
# 2   1 115900000 116260000 B8430        1          2          2
# 3   1 173500000 173680000    C5       -2         -2         -1
相关问题