Home > database >  Get the positions of a certain column in a data frame in ascending order in R
Get the positions of a certain column in a data frame in ascending order in R

Time:03-11

I would like to get the positions of the values in the second column of the dataframe below in ascending order but only for rows where the value of the first column is 0. Any idea how I could do this with the order function or anything else in R? My data frame is as follows:

par <- c(0,0,0,1,0,1,1,0)
par1 <- c(0.10,0.3,0.9,0.5,0.3,0.48,0.48,0.5)
p <- data.frame(par,par1)

CodePudding user response:

Looks like you are after which() that returns the index of the TRUE values, and sort() which pull arrange them in ascending order.

sort(which(p$par == 0))

#[1] 1 2 3 5 8

This gives you the row numbers where par == 0 which you can use as desired.

CodePudding user response:

You can use which to get the positions of the rows where p$par == 0, and then use order to reorder the vector based on ascending order.

which(p$par == 0)[order(p$par1[p$par == 0])]
# [1] 1 2 5 8 3
  •  Tags:  
  • r
  • Related