Question: Keep rows with different signs in two columns
1
gravatar for paolo002
3 months ago by
paolo002100
paolo002100 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 • 244 views
ADD COMMENTlink modified 3 months ago by zx87546.2k • written 3 months ago by paolo002100

Thanks a lot. It worked nicely.

ADD REPLYlink written 3 months ago by paolo002100
5
gravatar for ZZzzzzhong
3 months ago by
ZZzzzzhong190
ZZzzzzhong190 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 3 months ago by zx87546.2k • written 3 months ago by ZZzzzzhong190

Very nice, we could avoid creating a new column:

df1[ df1$col1 * df1$col2 < 0, ]
ADD REPLYlink written 3 months ago by zx87546.2k

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

ADD REPLYlink written 3 months ago by paolo002100
4
gravatar for zx8754
3 months ago by
zx87546.2k
London
zx87546.2k 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 3 months ago • written 3 months ago by zx87546.2k

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 3 months ago • written 3 months ago by paolo002100
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: 771 users visited in the last hour