Home > Software engineering >  How can I extract (values of yes) in vector from ifelse function
How can I extract (values of yes) in vector from ifelse function

Time:05-25

I want to extract values of yes in vector only in the ifelse function for example

X=rnorm(6,1,1)
 y<- ifelse(X>0,yes=1,no=2)
 #I get

1 1 2 1 1 1


#Also if I use for loop
  X<-matrix(rcauchy(15*5,0,1),5)


 p<-vector() 
for(i in 1:5){ 
p[i]<- ifelse (shapiro.test(X[i,])$p.value>=0.05,yes=t.test(X[i,], alternative = "two.sided")$p.value, no= wilcox.test(X[i,], mu = 0, alternative = "two.sided")$p.value)
 p


How can I extract (values of yes) from total result

CodePudding user response:

Maybe you want something like:

set.seed(7)
X <- matrix(rcauchy(15*5,0,1),5)
i <- apply(X, 1, \(y) shapiro.test(y)$p.value>=0.05)
apply(X[i,], 1, \(y) t.test(y, alternative = "two.sided")$p.value)
#[1] 0.5011835 0.6214762 0.0983801

Try.

set.seed(42)
X <- rnorm(6)

1[ (X > 0)]
#[1] 1 1 1 1

rep(1, sum(X>0))
#[1] 1 1 1 1

To get the values.

X[X > 0]
#[1] 0.7212112 0.8666787 1.6359504 0.7157471

To get values from another vector.

seq_along(X)[X > 0]
#[1] 2 3 4 5

Some also use which.

which(X>0)
#[1] 2 3 4 5

X[which(X>0)]
#[1] 0.7212112 0.8666787 1.6359504 0.7157471

CodePudding user response:

To keep your ifelse statement, then you can use it as an index by setting it equal to 1 to create a boolean vector. Then use [ to subset from original vector, i.e.

X[ifelse(X>0,yes=1,no=2) == 1]
#[1] 1.8418504 1.0860513 2.5771326 0.5809096 1.1458737 1.5731607
  •  Tags:  
  • r
  • Related