Keep rows with different signs in two columns
2
1
Entering edit mode
6.1 years ago
paolo002 ▴ 160

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 • 3.2k views
ADD COMMENT
0
Entering edit mode

Thanks a lot. It worked nicely.

ADD REPLY
5
Entering edit mode
6.1 years ago
ZZzzzzhong ▴ 240

You can define a new column:

df$3 = df$1 * df$2

then

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

Very nice, we could avoid creating a new column:

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

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

ADD REPLY
4
Entering edit mode
6.1 years ago
zx8754 12k

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 COMMENT
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 REPLY

Login before adding your answer.

Traffic: 2178 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6