检查列是否按降序排列

3
我希望检查列X是否按递减顺序排列,并且如果列X中有两个相同的值,则查看列Y中字母的字母顺序解决并列的情况。
以下是我目前的代码,但没有返回结果:
for (ii in 1:length(data_frame)) {
    if (ii == 1 | ii == length(data_frame)) {
      next
    } 
    else if (data_frame[["columnX"]][ii] == data_frame[["columnX"]][ii+1]) {
      ifelse(!is.unsorted(data_frame[["columnY"]][c(ii,ii+1)]),
             return(TRUE), 
             return(FALSE))
    }
  }

编辑:dput()

structure(list(Count = c(8184L, 8046L, 7988L, 7970L, 7771L, 7755L, 
7730L, 7650L, 7557L, 7428L), Name = c("Mary", "John", "Mary", 
"Mary", "Mary", "Robert", "Mary", "Mary", "John", "Mary")), .Names = c("Count", 
"Name"), row.names = c(4533L, 130862L, 3830L, 2456L, 6700L, 130863L, 
3150L, 5965L, 114094L, 5269L), class = "data.frame")

2
你能提供一些样本数据吗? - Jan
只是提供了样本数据! - user8248672
这意味着如果有两个相同的计数值,比如12后面跟着一个12,R就不能再根据计数来排序了...所以R会查看下一列(恰好是一个包含字符的列),并使用它的顺序来“打破”平局,并根据字母顺序确定行的顺序。 - user8248672
是的,完全正确,Sathish。 - user8248672
如果它不是按降序排列的,则返回FALSE。如果是,返回TRUE。 - user8248672
1
@JasonBaik,您的样本数据中Count值不同,但我的答案将适用于连续行中Count相同的情况。 - MKR
2个回答

1

使用dplyr的解决方案可以通过使用leadsummarise实现。

方法是首先找到当前行和下一行之间的差异。如果该差异大于0,则表示递减顺序。如果差异为0,则检查Name列(当前与下一个)的字母比较将决定递减顺序。

最后,如果DecOrder的所有值都在TRUE中,则表示Count按递减顺序排列。

library(dplyr)
df %>% mutate(DiffCount = Count - lead(Count, default=0)) %>%
  mutate(DecOrder = ifelse(DiffCount == 0, Name > lead(Name), DiffCount > 0)) %>%
  summarise(IsDesc = all(DecOrder))

#Result
#  IsDesc
#1   TRUE

数据

df <- structure(list(Count = c(8184L, 8046L, 7988L, 7970L, 7771L, 7755L, 
7730L, 7650L, 7557L, 7428L), Name = c("Mary", "John", "Mary", 
"Mary", "Mary", "Robert", "Mary", "Mary", "John", "Mary")), .Names = c("Count", 
"Name"), row.names = c(4533L, 130862L, 3830L, 2456L, 6700L, 130863L, 
3150L, 5965L, 114094L, 5269L), class = "data.frame")

0
检查列是否按降序排列:TRUE = 按降序排列; FALSE = 按升序排列或存在平局

x_diff <- diff(df1$Count)
d_order <- if( all(sign( x_diff ) == -1) ) TRUE else FALSE
d_order # [1] TRUE

检查第X列是否存在并列值,然后转到Y列,并检查相应的行是否按降序排列。若Y列按降序排列,则返回TRUE;若Y列按升序排列或存在并列值,则返回FALSE;若X列不存在并列值,则返回NULL

t_order <- if( any( duplicated( df1$Count ) ) ){
  lapply( with(df1, Count[ duplicated(Count) ] ), function(x){
    temp <- with(df1, Name[ Count == x ] )   # loop is used to iterate over multiple ties with different values (Example : 12 and 12; 15 and 15)
    all( temp[-length(temp)] > temp[-1] )
  } )
} else NULL

t_order # NULL

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接