我试图在R中编写一个带有嵌套if-else的函数,如何将列值设置为: data.frame:
输入
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预期产出
df <- read.table(header = TRUE, text="Chr start end num seg.mean seg.mean.1 seg.mean.2
1 68580000 68640000 A8430 1 0 1
1 115900000 116260000 B8430 1 2 2
1 173500000 173680000 C5 -2 -2 -1")
fun_cond <- function(x) { ifelse( x >= 1, 2,ifelse( x > 0 & x < 1, 1),ifelse( x <= 1, 2,ifelse( x < 0 & x > -1, -1)))}
new_df[5:length(df)] <- lapply(new_df[5:length(df)], fun_cond)发布于 2017-05-16 11:52:02
我想你想要的是:
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 & x > -1, -1, -2)))
}
> fun_cond(x)
#[1] -2 2 -2 -2 2 -2 1 1 -1试试吧..。
注意,
x == 0是-2。没有像您描述的那样的x <= 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发布于 2017-05-16 11:53:53
试试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 -1https://stackoverflow.com/questions/44000327
复制相似问题