检查列是否按降序排列

时间:2018-03-25 05:35:52

标签: r

我想检查列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 个答案:

答案 0 :(得分:1)

使用dplyrlead可以实现使用summarise的解决方案。

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

最后,如果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")

答案 1 :(得分: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; FALSE用于增加Y列的顺序或关系; NULL表示X列中没有任何关系。

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