R中两组变量的组合

  • 本文关键字:两组 变量 组合 r
  • 更新时间 :
  • 英文 :


我是R软件的新手,如果您能提供一些建议,将变量(抗生素(组合到通用变量(antibiotic_date(中,我将不胜感激。

我的原始数据如下(3X3表(;

  • id:1
  • 抗生素:a、b、c
  • 抗生素日期:2018-01-202018-01-202018-03-04

是否可以将上述日期转换为(3X表(;

  • id:1
  • 抗生素:a、b、c
  • 抗生素日期:2018-01-202018-03-04

非常感谢您的帮助。

看起来你有

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"

如果需要,也可以将sort包裹在它周围,例如sort(toString(unique(.)))


数据:

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))

最新更新