【问题标题】:How to edit data sets in R for multiple criteria?如何在 R 中为多个条件编辑数据集?
【发布时间】:2013-05-18 03:46:54
【问题描述】:

假设我在 R 中有一大组数据,其中包含变量纬度、经度、震级和深度(对于地震),我想创建一个新数据集,其中包含所有变量的数据,但仅在某些值之间纬度和经度。例如,我想要在 0 到 50 经度和 -20 到 45 纬度之间的地震(但我希望震级和深度仍然对应于正确的经度和纬度)。有没有一种简单的方法可以做到这一点?例如:

latitude longitude magnitude depth
45        45         1.0        5
-10       -10        4.5        6
-76       12         2.435      18

我想选择纬度在 -80 到 0 之间,经度在 0 到 50 之间的数据,所以唯一匹配的列是:

latitude, longitude magnitude depth
-76       12         2.435      18

我该怎么做?

【问题讨论】:

    标签: r variables csv edit


    【解决方案1】:
    > #Use [ to extract the rows directly
    > #See ?Comparison and ?Arithmetic for the operators
    > x[x$latitude > 0 & x$latitude < 80 & x$longitude > 0 & x$longitude < 50, ]
      latitude longitude magnitude depth
    1       45        45         1     5
    > #Or the slightly more readable subset() function
    > subset(x, latitude > 0 & latitude < 80 & longitude > 0 & longitude < 50)
      latitude longitude magnitude depth
    1       45        45         1     5
    > #see ?Extract or ?subset
    > #Also read the help manual for a good intro: http://cran.r-project.org/doc/manuals/R-intro.html
    

    【讨论】:

    • +1 for subset() 这是我认为最好的解决方案 - 正如你所说,可读
    • @PeterEllis - 可读性可能会以一些意想不到的后果为代价。帮助页面上写着类似this is a convenience function for interactive use. For programming it is better to use the standard subsetting functions like [... This post 的内容说明了原因。
    【解决方案2】:

    你可以索引你的data.frame,比如DF,如下:

    DF[DF$longitude >= 0 & DF$longitude <= 50 & 
       DF$latitude >= -20 & DF$latitude <=  45, ]
    
     latitude longitude magnitude depth
           45        45         1     5
    

    这是一个细分:

    [brackets] 中的语句正在索引 data.frame;更具体地说,data.frame 的

    R 中,您可以使用TRUE/FALSE 向量进行索引(除其他选项外)。因此,我们可以创建一个向量,当行在地理范围内时,其值为 TRUE,而在地理范围外时,其值为 FALSE

    定义边界是你盒子的四个“边”,即询问坐标是否在下限之上和上限之下。

    我们使用单个&amp; 运算符,而不是&amp;&amp;,因为我们希望每个 行都有一个唯一值。 如果最后一行不清楚,请查看以下内容之间的区别:

    x <- 1:5
    x > 1 &  x < 4
    
    # compare: 
    x > 1 && x < 4
    

    data.table 解决方案:

    如果您想使用 data.table 而不是 data.frame,它的学习曲线会稍长一些,但它的语法更简洁,工作更快:

    library(data.table)
    DT <- data.table(DF)
    
    DT[longitude >= 0 & longitude <= 50 & latitude >= -20 & latitude <=  45]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-29
      • 1970-01-01
      • 2020-11-07
      • 2020-07-26
      • 1970-01-01
      • 2020-07-16
      • 1970-01-01
      • 2013-11-13
      相关资源
      最近更新 更多