This is a test version of Biostars. For the public version, visit https://www.biostars.org.
Keep rows with different signs in two columns

Hi all, I have just a very simple question about subsetting data.

I have a data frame with many columns, two columns are indicating the fold change after RNA-seq data analysis. This two columns contain positive and negative values. I would like to keep the opposite values (negative in one column and positive in the other and vice versa) while removing those which are the same sign (negative and negative in the two columns or positive and positive).

Example:

df$1   df$2
 1.      2
-1.      1 
-1.      4
 3.     -2
 6.     -4
-6.     -6
 6.      1
-3.      7
......

 Resulting dataframe :

df$1.  df$2

-1.     1
-1.     4
 3.    -2
 6.    -4
-3.     7
......

Any help, highly appreciated, thanks!

r subset

Thanks a lot. It worked nicely.

2 answers

You can define a new column:

df$3 = df$1 * df$2

then

df <- subset(df, df$3 < 0, select = 1:2)

Very nice, we could avoid creating a new column:

df1[ df1$col1 * df1$col2 < 0, ]

yeah, nice, then it is possible to avoid creating the additional column in the data frame, thanks!

Check the columns signs then filter, try this example:

# reproducible example data
df1 <- read.table(text = "col1 col2
1. 2
-1. 1 
-1. 4
3. -2
6. -4
-6. -6
6. 1
-3. 7", header = TRUE)

# check if columns have the same sign, then filter
df1[ !(sign(df1$col1) == sign(df1$col2)), ]

#   col1 col2
# 2   -1    1
# 3   -1    4
# 4    3   -2
# 5    6   -4
# 8   -3    7

nice, this solution is very good, it checks the sign without doing any calculation on it, that was what I was looking for, no need of calculation and it does not create any additional column, thanks a lot!

Log in to answer this question.