如何在R中将IP地址转换为国家名称并保存为数据框新变量
修改方案:仅提取IP对应的国家全称
直接使用ip2location包中的get_country_long()函数替代get_all(),就能只获取国家全称,无需处理多余地理信息。修改后的完整代码如下:
df <- read.table(text=" ip_address 178.10.17.178 157.213.207.99 94.230.235.15 97.103.63.156 248.161.179.64 12.114.230.175 68.68.181.51 59.7.213.18 59.38.90.12 103.213.135.197", header = TRUE) install.packages('pacman') # load libraries pacman::p_load(ip2location, tidyverse) # 移除了reticulate,当前需求无需用到该包 # load IP2Location bin file ip2location::open("C:/Users/smbc1y19/Downloads/IP2LOCATION-LITE-DB1.BIN/IP2LOCATION-LITE-DB123.BIN") df <- df |> mutate(country_long = map_chr(ip_address, get_country_long)) df
核心修改点:
- 替换
get_all()为get_country_long():该函数专门返回IP对应的国家全称,不会返回region、city等额外地理变量 - 使用
map_chr()替代map():直接将每个IP的转换结果转为字符向量,避免生成列表列,因此无需再使用unnest_wider()展开数据 - 直接生成目标列
country_long:原数据框仅保留ip_address和新生成的country_long列,无多余字段
内容的提问来源于stack exchange,提问作者Sara C.
相关产品推荐
相关产品推荐

