【问题标题】:Display only rows values in which the difference in between a column is below 30仅显示列之间的差异小于 30 的行值
【发布时间】:2020-06-19 16:05:35
【问题描述】:

我一直尝试从 excel 文件中选择一个过滤器,其中只有“x”列中三个连续行值低于 30 个单位的行值。例如下表:

Name   age height speed
Helen  12. 1.20    40
Alan.  14. 1.40.   75
Hector.15. 1.25.   80
Ana.   11. 1.02.   81
Sophie.16. 1.40.   50

speed 列在连续行中的差异小于 30 时,它应该给出结果:

Name   age height speed
Alan.  14. 1.40.   75
Hector.15. 1.25.   80
Ana.   11. 1.02.   81

谢谢!!!

【问题讨论】:

    标签: r select filter rows data-manipulation


    【解决方案1】:

    如果你的数据是这样的:

    x = structure(list(Name = structure(c(4L, 1L, 3L, 2L, 5L), .Label = c("Alan", 
    "Ana", "Hector", "Helen", "Sophie"), class = "factor"), age = c(12, 
    14, 15, 11, 16), height = c(1.2, 1.4, 1.25, 1.02, 1.4), speed = c(40L, 
    75L, 80L, 81L, 50L)), class = "data.frame", row.names = c(NA, 
    -5L))
    

    希望我的数字是对的:

        Name age height speed
    1  Helen  12   1.20    40
    2   Alan  14   1.40    75
    3 Hector  15   1.25    80
    4    Ana  11   1.02    81
    5 Sophie  16   1.40    50
    

    然后做:

    x[diff(x$speed)<30,]
        Name age height speed
    2   Alan  14   1.40    75
    3 Hector  15   1.25    80
    4    Ana  11   1.02    81
    

    【讨论】:

    • 非常感谢!
    • 您写的内容适用于小表,但是,当您有一个超过一千行的excel并且您只想获得三个连续行之间的差异时,如何解决这个问题?我想过以下问题,但它给了我错误:
    • documentexcel = i) { x = 30: i = i + 1
    • 嘿,这完全不是另一个问题吗?我上面写的内容适用于您定义的问题。如果您有不同或更复杂的问题需要建议,请将其作为单独的问题发布
    【解决方案2】:

    下次您在这里发布时,发布一些如下的玩具数据信息会很有用:

    rm(list=ls())
    #### Toy data ###
    dfnames<-c("Name","age","height","speed")
    size<-20 # number of rows
    name<-LETTERS[1:size]
    age<-sample(20:26,size,replace=T)
    height<-sample(160:180,size,replace=T)
    speed<-sample(0:60,size,replace=T)
    df<-cbind.data.frame(name,age,height,speed)
    

    解决方案:

    for(i in 1:nrow(df)-1){
    df[i,"test"]<-(df[i+1,"speed"]-df[i,"speed"])<30
    }
    df[nrow(df),"test"]<-"last_row"
    df<-df[df[,"test"]!=F,]
    

    【讨论】:

    • 谢谢!下次我会更好地添加信息
    • 您写的内容适用于小表,但是,当您有一个超过一千行的excel并且您只想获得三个连续行之间的差异时,如何解决这个问题?我想过以下问题,但它给了我错误:
    • documentexcel = i) { x = 30: i = i + 1
    猜你喜欢
    • 2017-03-08
    • 1970-01-01
    • 1970-01-01
    • 2015-11-12
    • 2020-11-06
    • 2021-06-01
    • 2011-03-23
    • 2017-03-13
    • 2015-01-09
    相关资源
    最近更新 更多