简体   繁体   English

在R中使用ifelse条件转换值

[英]transform values with ifelse conditions in R

I am trying to read a huge matrix file in R and using ifelse to replace values with some conditions and having issues 我正在尝试在R中读取一个巨大的矩阵文件,并使用ifelse在某些条件下替换值并出现问题

INPUT 输入

     Input   A1    A2     B2    B3      B5
       a1   7.805   0   2.722   3.601   1.106
       a2   6.557   0   2.449   2.828   -2
       a3   5.899   2.333   2    0       0
       a4   5.779   7.517   0    0       0
       a5   5.52    0   1.633   1.342    0
     .......
     .......
       a300 -6.172  0     0      0      0.917
       a301 -6.24  -2.132 -2.218 -1.973  0
       a302 -6.436  0      0     1.516 4.611
       a303 -6.529  0      0       0    0
       a305 -6.607  -2.668  -2.883 0    0

i tried running below lines but in output i see its changing the conditions for some number of lines(random columns) and not all of them and row names are changing 我尝试在行下运行,但在输出中我看到其更改了一些行(随机列)的条件,但并非所有行和行名都在改变

  d <- read.table("input.txt",header=T,sep="\t",row.names=1,as.is=TRUE)
  s <- apply(d,2,function(x) ifelse(x>=3,1, ifelse(x<=-3,-1, ifelse(x<3|x>-3,0,x))) )  
  write.table(s,file="s.txt",sep="\t",quote=FALSE)

OUTPUT OF ABOVE SCRIPT 脚本的输出

  A1    A2  B2  B3  B5
  a1    1   0   0   1   0
  a2    1   0   0   0   0
  a3    1   0   0   0   0
  a4    1   1   0   0   0
  a5    1   0   0   0   0
 .....
 .....
 a300   -6.172  0     0      0      0.917
 a301   -6.24  -2.132 -2.218 -1.973  0
 a302   -6.436  0      0     1.516 4.611
 a303   -6.529  0      0       0    0
 a305   -6.607  -2.668  -2.883 0    0

can i get help in this? 我可以在这方面获得帮助吗?

Expected output 预期产量

    Input   A1  A2  B2  B3  B5
     a1     1   0   0   1   0
     a2     1   0   0   0   0
     a3     1   0   0   0   0
     a4     1   1   0   0   0
     a5     1   0   0   0   0
   .......

No need to use ifelse . 无需使用ifelse Your statement is equivalent to (x > 3) - (x < -3) . 您的陈述相当于(x > 3) - (x < -3)

So you could just use data.table : 因此,您可以只使用data.table

library(data.table)
d <- fread("input.txt")

d[ , lapply(.SD, function(x) (x > 3) - (x < -3))]

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

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