【问题标题】:Is there a way to append a column name to the end of each observation within respective columns?有没有办法将列名附加到各个列中每个观察的末尾?
【发布时间】:2022-12-06 07:53:47
【问题描述】:

[R] 我正在尝试修改我的数据框 (df) 的格式,以便将列名称附加到 R 中该列中的每个观察值。例如:

Soccer_Brand Basketball_Brand
Adidas Nike
Nike Under Armour

并想让它看起来像

Soccer_Brand Basketball_Brand
Adidas_Soccer_Brand Nike_Basketball_Brand
Nike_Soccer_Brand Under_Armour_Basketball_Brand

我正在尝试进行购物篮分析,最终需要删除列名称。但是,如果不将列名称附加到观察本身,我将丢失有关该品牌属于哪种运动的信息。基本上我无法判断“耐克”条目是属于足球还是篮球。

到目前为止,我已经使用 Excel 公式破解了一个解决方案,但希望我的 R 脚本是独立的。我还没有在 R 中找到任何解决方案。

【问题讨论】:

    标签: r rstudio


    【解决方案1】:

    你可以paste一个列名到它的内容中。只需遍历所有列。使用 lapply 这样做允许一行代码:

    df[] <- lapply(seq_along(df),(i) paste(df[[i]], names(df)[i], sep = "_"))
    

    导致

    df
    #>          Soccer_Brand              Basketball_Brand
    #> 1 Adidas_Soccer_Brand         Nike_Basketball_Brand
    #> 2   Nike_Soccer_Brand Under Armour_Basketball_Brand
    

    问题数据以可重现的格式

    df <- data.frame(Soccer_Brand     = c("Adidas", "Nike"),
                     Basketball_Brand = c("Nike", "Under Armour"))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-03
      • 2022-01-22
      相关资源
      最近更新 更多