Question: Keep rows with different signs in two columns
1
gravatar for paolo002
6 months ago by
paolo002140
paolo002140 wrote:

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!

subset R • 310 views
ADD COMMENTlink modified 6 months ago by zx87547.1k • written 6 months ago by paolo002140

Thanks a lot. It worked nicely.

ADD REPLYlink written 6 months ago by paolo002140
5
gravatar for ZZzzzzhong
6 months ago by
ZZzzzzhong200
ZZzzzzhong200 wrote:

You can define a new column:

df$3 = df$1 * df$2

then

df <- subset(df, df$3 < 0, select = 1:2)
ADD COMMENTlink modified 6 months ago by zx87547.1k • written 6 months ago by ZZzzzzhong200

Very nice, we could avoid creating a new column:

df1[ df1$col1 * df1$col2 < 0, ]
ADD REPLYlink written 6 months ago by zx87547.1k

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

ADD REPLYlink written 6 months ago by paolo002140
4
gravatar for zx8754
6 months ago by
zx87547.1k
London
zx87547.1k wrote:

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 modified 6 months ago • written 6 months ago by zx87547.1k

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 modified 6 months ago • written 6 months ago by paolo002140
Please log in to add an answer.

Help
Access

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.
Powered by Biostar version 2.3.0
Traffic: 1416 users visited in the last hour