1

我有一个大数据(.tr 文件)。我已阅读该文件并重命名数据框 (df) 中的列。我设法检查了所有现有记录并检查了某些条件。我需要计算整个文件中存在多少唯一值(来自 src.port 列)?以下 MWE 将说明我的问题。

# The df looks like:
     st time      from to protocol size flags    flowID src.port dst.port  seq   pktID
      + 0.100000    1   2      tcp   40 -------      1      5.0       2.1     0     0
      - 0.100000    5   0      ack   40 -------      1      5.1       2.3     0     0
      r 0.102032    1   2      tcp   40 -------      1      5.20      2.5     0     0
      r 0.102032    1   2      tcp   40 -------      1      5.11      2.6     0     0
      r 0.102032    1   2      tcp   40 -------      1      3.0       2.0     0     0
      + 0.121247   11   0      ack   40 -------      1      11.1      2.10    0     1
      r 0.132032    1   2      tcp   40 -------      1      3.0       2.0     0     0
      r 0.142065    1   2      tcp   40 -------      1      3.0       4.0     0     0

 # I have tried the following:
   unique<-0
  for (i in 1:nrow(df)){
    # feel free to suggest different way from the below line. 
    # I think using the name of column would be better 
    if(df[i,1]=="r" && df[i,3]== 1 && df[i,4]== 2 && df[i,5]== "tcp" ){
     # now this condition is my question
     # check if df[i,9] is new not presented before...Note 5.0 is different from 5.1 
     # check if df[i,10] is 2 and ignore any value after the dot (i.e 2.x ..X means any value)
     # so the condition would be:
      if ( df[i,9] is new not repeated && df[i,10] is 2.x)
          unique<-unique+1
     }

   } 

从样本数据的预期输出:是唯一的= 3

4

1 回答 1

0

您可以简单地对相关数据进行子集化并使用unique. 在这里,我将您的所有条件链接在一起,仅提取“scr.port”列并用于unique结果。

unique(mydf[mydf[, "st"] == "r" & 
              mydf[, "from"] == 1 & 
              mydf[, "protocol"] == "tcp" & 
              grepl("^2.*", mydf[, "dst.port"]), 
            "src.port"])
# [1] 5.20 5.11 3.00

将其包裹起来length以获得您正在寻找的计数。

或者,创建数据子集并计算行数。

out <- mydf[mydf[, "st"] == "r" & 
              mydf[, "from"] == 1 & 
              mydf[, "protocol"] == "tcp" & 
              grepl("^2.*", mydf[, "dst.port"]), ]
nrow(out[!duplicated(out$src.port), ])
# [1] 3
于 2013-10-26T03:02:32.837 回答