【问题标题】:How to loop vectors through a function that takes only two values at a time in R?如何通过在R中一次只取两个值的函数循环向量?
【发布时间】:2021-07-04 04:17:36
【问题描述】:
lat <- c(45.08323,40.08323)
long <- c(-82.46797,-81.46797)
df <- data.frame(lat, long)

library(geonames) #To calibrate altitude
readLines(url("http://api.geonames.org/",open="r"))
options(geonamesUsername= "MyUsername") #Note you have to create a username one the 
website AND enable webservices on your geonames user account at 
https://www.geonames.org/manageaccount. 

GNsrtm3(54.481084,-3.220625)

   srtm3       lng      lat
1   797 -3.220625 54.48108

GNsrtm3 一次只能接受两个值,但我想通过函数运行一个纬度和经度向量。我希望将所有三个值 strm3、lng 和 lat 存储在 data.frame df.results 中。我不擅长循环,但我尝试过

  for(i in 1:length(df)){
  df.result <- GNsrtm3(df$lat[i],df$long[i])
  i = i + 1 }

  df$alt <- df.result$srtm3

我只得到答案的第一行。所以它不接受向量。有什么见解吗?

【问题讨论】:

  • 使用“nrow”代替“length”。数据帧的长度是列数,因为它是一个列表。并且不要增加循环计数器。它作为“for”函数的一部分自动发生。

标签: r loops for-loop


【解决方案1】:

您当前正在每次迭代中覆盖df.result 中的值。同样for 循环不需要i = i+ 1,它会自动增加i 的值。

初始化一个列表以存储每次调用的值,并在循环结束时将它们绑定在一起以获得一个组合数据帧。

df.result <- vector('list', nrow(df))

for(i in seq(nrow(df))){
  df.result[[i]] <- GNsrtm3(df$lat[i],df$long[i])
}

df.result <- do.call(rbind, df.result)

不涉及显式 for 循环的其他一些替代方案是 -

df.result <- do.call(rbind, Map(GNsrtm3, df$lat, df$long))
df.result <- purrr::map2_df(df$lat, df$long, GNsrtm3)

【讨论】:

    猜你喜欢
    • 2021-04-18
    • 2021-12-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-02
    • 1970-01-01
    • 2019-05-29
    • 1970-01-01
    • 2022-01-17
    相关资源
    最近更新 更多