【问题标题】:Modifying a function in R to add ID information?修改R中的函数以添加ID信息?
【发布时间】:2013-11-26 15:06:49
【问题描述】:

我一直在使用来自 Heuristic Andrew 博客和 StackOverflow Question 的这个很棒的代码。

我想做一个简单的修改,使我的最终输出也包含来自原始数据帧的 ID 信息。这是我现在拥有的代码

test1 <- structure(list(ID = c("A123", "A123", "A125", "A126"),
                        IP = c("173.74.6.149", "109.189.227.94",
                               "50.27.115.146", "1.64.170.178")),
                   .Names = c("ID", "IP"), class = "data.frame",
                   row.names = c(NA, 4L))

freegeoip <- function(ip, format = ifelse(length(ip)==1,'list','dataframe'))
{
  if (1 == length(ip))
  {
    # a single IP address
    require(rjson)
    url <- paste(c("http://freegeoip.net/json/", ip), collapse='')
    ret <- fromJSON(readLines(url, warn=FALSE))
    if (format == 'dataframe')
      ret <- data.frame(t(unlist(ret)))
    return(ret)
  } else {
    ret <- data.frame()
    for (i in 1:length(ip))
    {
      r <- freegeoip(ip[i], format="dataframe")
      ret <- rbind(ret, r)
    }
    return(ret)
  }
} 

try.ip   <- function(ip) suppressWarnings(try(freegeoip(ip), silent = TRUE))
outcomes <- lapply(test1$IP, try.ip)

is.ok    <- function(x) !inherits(x, "try-error")

outcomes <- outcomes[sapply(outcomes, is.ok)]
outcomes <- do.call("rbind", outcomes)

我认为正确的做法是修改freegeoip 函数,但我不确定如何。

谁能帮帮我?

【问题讨论】:

    标签: r


    【解决方案1】:

    编辑 - 更新为仅添加一个 ID 列

    在代码末尾添加,只需查找 IP,并将 ID 添加为新列:

    outcomes<-data.frame(outcomes)
    outcomes$ID<-apply(outcomes,1,FUN=function(x)test1$ID[match(x["ip"],test1$IP)])
    

    *********上一个答案*****************

    如果你改变函数,问题是你会改变输入数据的形状,并且需要相当大的重写它。

    如果您只想将结果添加到结果列,为什么不试试merge()

    idcols<-test1 # make a temp copy of the test1 table
    colnames(idcols)<-c("id","ip") # make the ip column header identical to outcomes
    merge(idcols,outcomes,by="ip") # merge by ip
    

    给予:

                      ip   id country_code  country_name region_code region_name    city zipcode latitude  longitude
        1 109.189.227.94 A123           NO        Norway          12        Oslo    Oslo          59.9167     10.75
        2   173.74.6.149 A123           US United States          TX       Texas  Keller   76244  32.9346  -97.2517
        3  50.27.115.146 A125           US United States          TX       Texas Midland          31.9974 -102.0779
        metro_code areacode
        1                    
        2        623      817
        3        633      432
    

    【讨论】:

    • 谢谢@Troy。但是,如果我有多个具有相同 IP 的用户会怎样?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-26
    • 2020-05-19
    • 2021-02-23
    • 2013-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多