看起来你有
df
# id antibiotic antibiotic_date
# 1 1 a 2018-01-20
# 2 1 b 2018-01-20
# 3 1 c 2018-03-04
在aggregate 中使用unique。
(res1 <- aggregate(. ~ antibiotic_date, df, unique))
# antibiotic_date id antibiotic
# 1 2018-01-20 1 a, b
# 2 2018-03-04 1 c
在哪里
str(res1)
# 'data.frame': 2 obs. of 3 variables:
# $ antibiotic_date: chr "2018-01-20" "2018-03-04"
# $ id : chr "1" "1"
# $ antibiotic :List of 2
# ..$ : chr "a" "b"
# ..$ : chr "c"
如果您需要一个字符串而不是长度 > 1 的向量,请将其设为toString,
(res2 <- aggregate(. ~ antibiotic_date, df, (x) toString(unique(x))))
# antibiotic_date id antibiotic
# 1 2018-01-20 1 a, b
# 2 2018-03-04 1 c
在哪里:
str(res2)
# 'data.frame': 2 obs. of 3 variables:
# $ antibiotic_date: chr "2018-01-20" "2018-03-04"
# $ id : chr "1" "1"
# $ antibiotic : chr "a, b" "c"
或paste,
(res3 <- aggregate(. ~ antibiotic_date, df, (x) paste(unique(x), collapse=' ')))
# antibiotic_date id antibiotic
# 1 2018-01-20 1 a b
# 2 2018-03-04 1 c
在哪里:
str(res3)
# 'data.frame': 2 obs. of 3 variables:
# $ antibiotic_date: chr "2018-01-20" "2018-03-04"
# $ id : chr "1" "1"
# $ antibiotic : chr "a b" "c"
数据:
df <- structure(list(id = c(1, 1, 1), antibiotic = c("a", "b", "c"),
antibiotic_date = c("2018-01-20", "2018-01-20", "2018-03-04"
)), class = "data.frame", row.names = c(NA, -3L))