標籤:string user table lis info tor tin code color
======================================================================================
data:
have <- data.frame(ID=paste0("id", c(101, 102, 102, 103, 103, 104, 105, 105)),
info1=c("one", "twoA", "twoB", "threeA", "threeB", "four", "five", "five"),
stringsAsFactors=FALSE)
want <- data.frame(ID=paste0("id", c(101:105)),
info1=c("one", "twoA; twoB", "threeA; threeB", "four", "five"),
stringsAsFactors=FALSE)
======================================================================================
MySQL
SELECT user_id, COUNT(id) AS freq, GROUP_CONCAT(DISTINCT ip SEPARATOR ",") AS ipsFROM log_tableGROUP BY user_idORDER BY freq ASC;
======================================================================================
R&SQL
library(sqldf)
sqldf("
SELECT ID,
GROUP_CONCAT(distinct info1) as info1
FROM have
GROUP BY ID")
註:此種情況沒能實現更改間隔符,預設為逗號。
======================================================================================
R
--------------------------------------------------------------------------------------------------------------------------------------
require(dplyr)
METHOD1: have %>% group_by(ID) %>% summarise_each(funs(toString(sort(unique(info1)))))
METHOD2: have %>% group_by(ID) %>% summarise(name = toString(sort(unique(info1))))
--------------------------------------------------------------------------------------------------------------------------------------
require(data.table)
METHOD1: setDT(have)[, .(info1 = toString(sort(unique(info1)))), by = ID]
METHOD2: setDT(have)[ , .(info1 = paste(unique(info1), collapse = ",")),by = ID]
註:paste函數作為其他函數的參數時,不能。例如
aggregate(have[,2], by=list(have$ID), paste(unique(info1)), collapse=";") ×
aggregate(have[,2], by=list(have$ID), paste, collapse=";") √
setDT(have)[, lapply(.SD, paste(unique(info1)), collapse = "; "), by = ID] ×
setDT(have)[, lapply(.SD, paste, collapse = "; "), by = ID] √
--------------------------------------------------------------------------------------------------------------------------------------
aggregate(data=have,info1~ID,FUN = function(t) sort(unique(t)))
R&SQL合并記錄並去重