我正在R中进行一些编码。我想显示列ID和NAME重复的行,但AGE的值不同。
例如我有这张表:
ID | NAME | AGE
111| Mark| 22
222| Anne| 21
333| Chery| 30
444| Megan| 16
555| Charles| 37
111| Mark| 23
222| Anne| 22
333| Chery| 30
111| Mark| 22
截至目前,我有这段代码:
readfile <- read.csv(file='/home/user/shane/names.csv')
dat <- data.frame(ID=c(readfile$ID),NAME=c(readfile$NAME),AGE=c(readfile$AGE))
nam <- duplicated(dat[,c('ID','NAME)]) | duplicated(dat[,c('ID','NAME], fromLast = TRUE)
readfile[nam,]
输出如下:
ID | NAME | AGE
111| Mark| 22
222| Anne| 21
333| Chery| 30
111| Mark| 23
222| Anne| 22
333| Chery| 30
111| Mark| 22
我希望输出为:
ID | NAME | AGE
111| Mark| 22
222| Anne| 21
111| Mark| 23
222| Anne| 22
111| Mark| 22
我想删除ID = 333的列,因为它们在Age中具有相同的值。有人会有什么建议吗?
答案 0 :(得分:6)
我只是调整了你的代码:)
library(plyr)
dat1 <- ddply(dat, .(ID, NAME, AGE), nrow)
dat2 <- merge(dat1, dat, by=c("ID", "NAME", "AGE"))
dat3 <- dat2[!(!duplicated(dat2[, 1:2], fromLast=T) & !duplicated(dat2[, 1:2])),]
dat3[dat3$ID %in% dat3[dat3$V1 == 1, 1], 1:3]
输出为:
ID NAME AGE
1 111 Mark 22
2 111 Mark 22
3 111 Mark 23
4 222 Anne 21
5 222 Anne 22
示例数据:
dat <- data.frame(ID=c(111,222,333,444,555,111,222,333,111),
NAME=c('Mark','Anne','Chery','Megan','Charles','Mark','Anne','Chery','Mark'),
AGE=c(22,21,30,16,37,23,22,30,22))
# ID NAME AGE
#1 111 Mark 22
#2 222 Anne 21
#3 333 Chery 30
#4 444 Megan 16
#5 555 Charles 37
#6 111 Mark 23
#7 222 Anne 22
#8 333 Chery 30
#9 111 Mark 22
更新:更正了格式以便更好地阅读
答案 1 :(得分:2)
$sql = "select u.*, (select GROUP_CONCAT(name) from projects as p where p.user_id = u.id_user) as projects, (select GROUP_CONCAT(name) from categories as c where c.id_cat in (select cat_id from users_categories where user_id = u.id_user)) as categories from users as u";
$query = $this->db->query($sql);
$result = $query->result_array();
解决方案:
dplyr
我使用了@Prem友情提供的数据。
答案 2 :(得分:1)
以下是data.table
library(data.table)
setDT(dat)[, .SD[.N >1 & !sum(duplicated(AGE))], by = .(ID, NAME)]
# ID NAME AGE
#1: 111 Mark 22
#2: 111 Mark 23
#3: 222 Anne 21
#4: 222 Anne 22