Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 数据表用户定义函数_R_Data.table - Fatal编程技术网

R 数据表用户定义函数

R 数据表用户定义函数,r,data.table,R,Data.table,我有一个data.table,其中有一列列出了正在装运的货物的协调关税代码。存在一些输入问题,因为有时一行可能有重复的数字“7601.00;7601.00”,有时可能有不同的数字“7601.00;8800.00”。当我有不同的条目时,我还没有决定要做什么,但我想做的第一件事是去掉重复的条目。因此,我编写了一个自定义的用户定义函数: unique_hscodes <- function(hs_input){ new <- strsplit(hs_input, split = "

我有一个data.table,其中有一列列出了正在装运的货物的协调关税代码。存在一些输入问题,因为有时一行可能有重复的数字“7601.00;7601.00”,有时可能有不同的数字“7601.00;8800.00”。当我有不同的条目时,我还没有决定要做什么,但我想做的第一件事是去掉重复的条目。因此,我编写了一个自定义的用户定义函数:

unique_hscodes <- function(hs_input){


  new <- strsplit(hs_input, split = ";")                   # Delimiter ;
  new <- lapply(new, str_replace_all, " ", "")

  if (length(unique(unlist(new))) == 1) {                  # Unique HS code
    return(unique(unlist(new)))
  }  
  else {

  new <- names(sort(table(unlist(new)),decreasing=TRUE)[1]) # Most frequent

  return(new) 

  } 

}

unique\hscode您的代码在字符串拆分后从单个项目输入返回多个项目。使用by=1:nrow(DT)运行时,一次只检查一行。如果只显示一行,则不会出现此问题

 DT <- data.table(hscode=c("7601.00; 7601.00" , "7601.00; 8800.00"))
 DT
#-----
             hscode
1: 7601.00; 7601.00
2: 7601.00; 8800.00
#--
 DT[ ,  table( unlist( strsplit(hscode, split="; "))) ]

#7601.00 8800.00 
#      3       1 
 DT[ ,  table( unlist( strsplit(hscode, split="; "))) , by=1:nrow(DT)]
#---------
  nrow V1
1:    1  2
2:    2  1
3:    2  1

欢迎来到StackOverflow!请阅读相关信息以及如何给出建议。这将使其他人更容易帮助你。也许
DT[,hs_code:=sapply(hscode,unique_-hscode)]
有效?我想整个问题是为什么,因为
by
操作是“有效的”。@Frank:我想我认为另一个代码实际上是“去除重复项”,但我现在明白了。
> DT[, hs_code := sapply(hscode, unique_hscodes)]
> DT
             hscode hs_code
1: 7601.00; 7601.00 7601.00
2: 7601.00; 8800.00 7601.00