R语言 如何比较R数据框架中的两列

R语言 如何比较R数据框架中的两列

在这篇文章中,我们将讨论如何通过R编程语言比较数据框架中的两列。

我们可以通过使用ifelse()在R中比较两列。该语句用于检查给定的条件并返回相应的数据。

语法:

ifelse(dfcolumn1>dfcolumn2, statement,............)
Bash

其中。

  • df是输入的数据框架
  • 列是给定数据框架中的列

例子:

让我们创建一个有两列的数据框架

# dataframe
data = data.frame(column1=c(90, 76, 89), 
                  column2=c(89, 79, 100))
  
# display
data
Bash

输出:

如何比较R数据框架中的两列?

例1 :

在这里,我们将检查列1的值是否更大,如果更大,则添加一个名为results的新列并将其分配给Column1。如果列2的值更大,则添加一个新的列,命名为results,并将其分配给Column2,否则没有。

# dataframe
data = data.frame(column1=c(90, 76, 89),
                  column2=c(90, 79, 100))
  
# check if column1 value is greater - if greater 
# then add a new column named results and assign
# with Column1
# if column2 value is greater - if greater then
# add a new column named results and assign with 
# Column2 otherwise None
dataresults = ifelse(datacolumn1 > datacolumn2, 'Column1',
                      ifelse(datacolumn1 < data$column2, 'Column2', 'None'))
  
  
# display
data
Bash

输出 :

如何比较R数据框架中的两列?

例2 :

在这里,我们将检查列1的值是否更大,然后添加一个名为results的新列,并将其分配给列1;如果列2的值更大,则添加一个名为results的新列,并将其分配给列2。

# dataframe
data = data.frame(column1=c(70, 76, 89), 
                  column2=c(90, 79, 100))
  
# check if column1 value is greater - if 
# greater then add a new column named results
# and assign with Column1
# if column2 value is greater - if greater then
# add a new column named results and assign with 
# Column2 otherwise None
dataresults = ifelse(datacolumn1 > datacolumn2, 'Column1',
                      ifelse(datacolumn1 < data$column2, 'Column2', 'None'))
  
  
# display
data
Bash

输出:

如何比较R数据框架中的两列?

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册