R-数据表用户定义的功能



我有一个数据。表列列列出了正在运送的商品的统一关税代码。有一些输入问题,因为有时一排可能重复的数字" 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) 
  } 
}

当我这样做时,DT[, hs_code := unique_hscodes(hscode)]它会将带有相同数字的列HS_Code的数据表返回我。但是当我做DT[, hs_code := unique_hscodes(hscode), by =1:nrow(DT)]时,它可以正确完成。

有人可以解释一下这里发生了什么吗?

您的代码在字符串拆分后从单个项目输入中返回多个项目。当您使用= 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

我尝试了一个简单的示例 @jaap的代码

> 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

最新更新