将IP地址(IPv4)转换为R中的整数 [英] Convert IP address (IPv4) itno an Integer in R

查看:672
本文介绍了将IP地址(IPv4)转换为R中的整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找一种在R中编写函数的方法,它将IP地址转换为整数。

I was looking for a way to write a function in R which converts an IP address into an integer.

我的数据框如下所示:

total  IP
626    189.14.153.147
510    67.201.11.8
509    64.22.53.140
483    180.9.85.10
403    98.8.136.126
391    64.06.187.68

我出口这个数据来自mysql数据库。我有一个查询,我可以将IP地址转换为mysql中的整数:

I export this data from mysql database. I have a query where i can convert an IP address into an integer in mysql:

mysql> select CAST(SUBSTRING_INDEX(SUBSTRING_INDEX('75.19.168.155', '.', 1), '.', -1) << 24 AS UNSIGNED) + CAST(SUBSTRING_INDEX(SUBSTRING_INDEX('75.19.168.155', '.', 2), '.', -1) << 16 AS UNSIGNED) + CAST(SUBSTRING_INDEX(SUBSTRING_INDEX('75.19.168.155', '.', 3), '.', -1) << 8 AS UNSIGNED) + CAST(SUBSTRING_INDEX(SUBSTRING_INDEX('75.19.168.155', '.', 4), '.', -1) AS UNSIGNED) FINAL;

但是我想在R中做这个转换,任何帮助都会很棒

But I want to do this conversion in R, any help would be awesome

推荐答案

你并不完全具体说明你想要什么样的转换,所以我将小数值乘以我认为合适的值(想想三位数的项目实际上是base 256数字中的数字等价物然后在基数10中重新显示。如果你想要颠倒地点的顺序,正如我在其他地方所建议的那样,你可以在两个解决方案中反转'vals'的索引

You were not entirely specific about what conversion you wanted, so I multiplied the decimal values by what I thought might appropriate (thinking the three digit items were actually digit equivalents in "base 256" numbers then redisplayed in base 10). If you wanted the order of the locations to be reversed, as I have seen suggested elsewhere, you would reverse the indexing of 'vals' in both solutions

 convIP <- function(IP) { vals <- read.table(text=as.character(IP), sep=".")
               return( vals[1] + 256*vals[2] + 256^2*vals[3] + 256^3*vals[4]) }

> convIP(dat$IP)
          V1
1 2476281533
2  134990147
3 2352289344
4  173345204
5 2122844258
6 1153107520

(通常更好的IT实践是指定您认为正确的答案,以便进行测试.Bertelson的评论以上会更快,并且隐含地使用1000,1000 ^ 2和1000 ^ 3作为因素。)

(It's usually better IT practice to specify what you think to be the correct answer so testing can be done. Bertelson's comment above would be faster and implicitly uses 1000, 1000^2 and 1000^3 as the factors.)

我正在努力简化代码,但担心需要使用 Reduce(+,...)可能会使它更复杂。您不能使用 sum ,因为它没有矢量化。

I am taking a crack at simplifying the code but fear that the need to use Reduce("+", ...) may make it more complex. You cannot use sum because it is not vectorized.

 convIP <- function(IP) { vals <- read.table(text=as.character(IP), sep=".")
                return( Reduce("+", vals*256^(3:0))) }

> convIP(dat$IP)
[1] 5737849088    5112017 2717938944    1245449 3925902848   16449610

这篇关于将IP地址(IPv4)转换为R中的整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆