【问题标题】:Combining two sets of variable in R在R中组合两组变量
【发布时间】:2022-10-05 09:46:45
【问题描述】:

我对 R 软件非常陌生,如果您能提供一些建议以将变量(抗生素)组合到公共变量(antibiotic_date)中,我将不胜感激。

我的原始数据看起来像这样(3X3 表);

  • 标识:1
  • 抗生素:a、b、c
  • antibiotic_date: 2018-01-20, 2018-01-20, 2018-03-04

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

  • 标识:1
  • 抗生素:a b, c
  • antibiotic_date: 2018-01-20, 2018-03-04

非常感谢您的帮助。

【问题讨论】:

    标签: r


    【解决方案1】:

    看起来你有

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

    【讨论】:

    • 非常感谢。有效。但是,2018-01-20 上的联合抗生素 (a,b) 在我的数据框中显示为 c("a", "b'),当我尝试 str_match(antibiotic, "a") 时,它显示错误消息, “参数不是原子向量;强制”。我认为此错误消息是由于变量为 c("a", "b") 而不是 a,b。您对此有什么建议吗?谢谢
    • @zinc54574 是的,请查看更新。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-26
    • 1970-01-01
    • 2015-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多