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

循环数据帧行并在新列中添加值(R),r,for-loop,if-statement,dataframe,row,R,For Loop,If Statement,Dataframe,Row,我有一个带有纬度(Lat)列的数据帧(df),我需要匹配相应的经度值(基于另一个数据集中的关系)。新列名为“Long_matched” 在这里,我试图在相应行的“Long_matched”列中写入一个新值,以表示-33.9238和-33.9236之间的纬度。“Lat”中的数据有更多的小数位(例如:-33.92380266667,-33.92360266667等)。由于我将把这段代码应用于同一地理位置上的多个数据集(因此长小数将略有不同),所以我想写0.0002度范围内的经度值 我尝试过的一些代码

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

在这里,我试图在相应行的“Long_matched”列中写入一个新值,以表示-33.9238和-33.9236之间的纬度。“Lat”中的数据有更多的小数位(例如:-33.92380266667,-33.92360266667等)。由于我将把这段代码应用于同一地理位置上的多个数据集(因此长小数将略有不同),所以我想写0.0002度范围内的经度值

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

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

评论中所说的一切都适用,但这里有一个技巧你可以尝试: 在下面的代码中,需要将文本替换为数字

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]
})

Latitude\u breaks评论中所说的一切都适用,但这里有一个技巧你可以试试:
在下面的代码中,需要将文本替换为数字

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]
})

Latitude\u breaks您是否尝试在“Lat”的相邻元素之间进行比较?发布几行示例输入。您的代码令人困惑,因为第一行修改了
df
,第二行修改了名为
df\u avg
。。。可能您只需要
合并(df1,df2)
?但是如果没有样本输入和期望的输出,很难判断。不,我只想在行的“Long_matched”列中添加一个新值,该值与特定的“Lat”值匹配。我已经知道我要添加的值是什么。你能将Lat四舍五入到一个直接匹配的数字吗?如果你使用
“N/a”
,整个列将被强制为class
character
。你想在“Lat”的相邻元素之间进行比较吗?发布几行示例输入。您的代码令人困惑,因为第一行修改了
df
,第二行修改了名为
df\u avg
。。。可能您只需要
合并(df1,df2)
?但是如果没有样本输入和期望的输出,很难判断。不,我只想在行的“Long_matched”列中添加一个新值,该值与特定的“Lat”值匹配。我已经知道我要添加的值是什么。你能将Lat四舍五入到一个数字以直接匹配吗?如果你使用
“N/a”
,整个列将强制为class
字符
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]
})