R语言 从R数据框中选择同时包含正值和负值的行

R语言 从R数据框中选择同时包含正值和负值的行

在这篇文章中,我们将讨论如何在R编程语言中选择包含正值和负值的数据框中的行。为了更好地理解,让我们举一个例子。

假设你在R语言中拥有以下数据框,其中包含多列和多行。所有的行都包含负值或正值,或者可能两者都包含,如下所示。

正在使用的数据框

ID temp_1 temp_2 temp_3 temp_4 temp_5
1. -74 88 39 -64 -83
2. -89 52 37 -26 -39
3. 34 -28 -39 -54 -53
4. -82 -19 -64 -33 -20
5. -64 39 -93 -43 -31
6. 92 86 44 23 82
7. -67 -31 38 63 -17

因此,我们的任务是只选择那些同时包含正值和负值的行。选择数值后,我们的数据框应该是这样的。

预期的输出

ID temp_1 temp_2 temp_3 temp_4 temp_5
1. -74 88 39 -64 -83
2. -89 52 37 -26 -39
3. 34 -28 -39 -54 -53
5. -64 39 -93 -43 -31
7. -67 -31 38 63 -17

我们将从数据框中抽取一个子集,如果且仅有任何一行包含大于0和小于0的值,否则,我们将不考虑它。

语法

subset(x,(rowSums(sign(x)<0)>0) & (rowSums(sign(x)>0)>0))

这里,x是数据框的名称。

方法

  • 创建数据集
  • 应用subset()
  • 选择同时具有负值和正值的行
  • 显示这些行

例子

# To select rows in dataframe 
# that contains both positive and negative values
  
# Creating dataset 
# creating fisrs column
first <- c(-74,-89,34,-82,-64,92,-67)
  
# creating second column
second <- c(88,52,-28,-19,39,86,-31)
  
# creating third column
third <- c(39,37,-39,-64,-93,44,38)
  
# creating fourth column
fourth <- c(-64,-26,-54,-33,-43,23,63)
  
# creating fifth column
fifth <- c(-83,-39,-53,-20,-31,82,-17)
  
# creating dataframe
x <- data.frame(temp_1=first,
                 temp_2=second,temp_3=third,
                 temp_4=fourth,temp_5=fifth)
  
# checking if there exist a row with 
# both positive and negative values
subset(x,(rowSums(sign(x)<0)>0) & (rowSums(sign(x)>0)>0))
R

输出

从R数据框中选择同时包含正值和负值的行

图1

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册