奢香夫人1 发表于 2017-7-29 22:41 
谢谢谢谢!我刚用了很多数据做测试,可是我又发现了一个问题哎
对于你的测试数据来说,当重复ID是最小 ...
已经修改了代码,因为by()函数会自动把结果按照ID 从小到大排列,我加了一行代码
site <- site[as.character(unique(sub.dat$ID))]
把他按照看到的ID的顺序排列。 如果还有问题请在留言:
##define data frame
dat <- data.frame(ID=c(8,8,4,5),SITE=c('beijing','shanghai','beijing','beijing'),Volume=c(1,1,4,5))
dat
##create new site names
sub.dat <- dat[,c('ID','SITE')]
site <- by(data=sub.dat,INDICES = sub.dat$ID,FUN = function(x){
paste0(x$SITE,collapse = ',')
})
site <- site[as.character(unique(sub.dat$ID))]
site.idx <- which(colnames(dat)=='SITE')
##remove duplicated and put in the new site names
dat.new <- dat[!duplicated(dat[,-site.idx]),]
dat.new$SITE <- as.vector(site)
dat.new