首页 文章

循环遍历数据帧行并在新列中添加值(R)

提问于
浏览
0

我有一个带有Latitude(Lat)列的数据帧(df),我需要匹配相应的Longitude值(基于另一个数据集中的关系) . 新列名称为“Long_matched” .

在这里,我试图在相应行的'Long_matched'列中写一个新值到-33.9238和-33.9236之间的纬度 . 'Lat'中的数据有更多小数位(例如:-33.9238026666667,-33.9236026666667等) . 由于我将此代码应用于同一地理位置的多个数据集(因此长小数会略有不同),我想编写落在0.0002度范围内的经度值 .

我试过的一些代码尝试包括:

df$Long_matched <- ifelse(df$Lat< -33.9236 & df$Lat> -33.9238, 151.2279 , "N/A")

要么

df$Long_matched[df$Lat< -33.9236 & df$Lat> -33.9238] <- 151.2279

我想我需要使用for循环遍历行和if语句,但努力想出这个 - 任何帮助都将不胜感激!

结果输出应如下所示:

Lat                   Long_matched
-33.9238026666667     151.2279
-33.9236026666667     (new long value will go here)

1 回答

  • 3

    注释中的所有内容都适用,但这是一个可以尝试的技巧:在下面的代码中,您需要用数字替换文本 .

    Latitude_breaks <- seq(min_latitude, max_latitude, 0.0002) # you need to replace `min_latitude`, `max_latitude`, and `increment` with numbers
    Longitude_values <- seq(first, last, increment) # you need to replace `first`, `last` and `increment` with numbers
    df <- within(df, {
      # make a categorical version of `Lat`
      Lat_cat <- cut(Lat, Latitude_breaks)
      Long_matched <- Longitude_values[Lat_cat]
    })
    

    几点说明:

    • min_latitudemin_latitude + 1 之间的值将分配给首先标记的 Longitude 的值 .

    • Latitude_beaks 的长度应该比 Longitude_values 的长度多一个 .

    • Latitude_breaks 之外的 Lat 的值将变为NA .

    这通过利用因子的一个很好的特征来工作 - 它们被存储为整数 . 所以我们可以用它们来索引另一个向量 - 在这种情况下, Longitude_values .

相关问题