Biostar Beta. Not for public use.
Keep rows with different signs in two columns
1
Entering edit mode
21 months ago
paolo002 • 140

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 • 371 views
ADD COMMENTlink
0
Entering edit mode

Thanks a lot. It worked nicely.

ADD REPLYlink
5
Entering edit mode
14 months ago
ZZzzzzhong • 200

You can define a new column:

df$3 = df$1 * df$2

then

df <- subset(df, df$3 < 0, select = 1:2)
ADD COMMENTlink
0
Entering edit mode

Very nice, we could avoid creating a new column:

df1[ df1$col1 * df1$col2 < 0, ]
ADD REPLYlink
0
Entering edit mode

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

ADD REPLYlink
4
Entering edit mode
4 months ago
zx8754 7.5k
London

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
ADD COMMENTlink
0
Entering edit mode

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!

ADD REPLYlink

Login before adding your answer.

Similar Posts
Loading Similar Posts
Powered by the version 2.1