简体   繁体   English

有没有办法将 append 列名添加到各个列中每个观察的末尾?

[英]Is there a way to append a column name to the end of each observation within respective columns?

[R] I am trying to modify the format of my data frame (df) so that the column name is appended to each observation within that column within R. For example: [R] 我正在尝试修改我的数据框 (df) 的格式,以便将列名称附加到 R 内该列中的每个观察值。例如:

Soccer_Brand足球品牌 Basketball_Brand篮球_品牌
Adidas阿迪达斯 Nike耐克
Nike耐克 Under Armour安德玛

And want to get it to look like并想让它看起来像

Soccer_Brand足球品牌 Basketball_Brand篮球_品牌
Adidas_Soccer_Brand阿迪达斯足球品牌 Nike_Basketball_Brand耐克_篮球_品牌
Nike_Soccer_Brand耐克_足球_品牌 Under_Armour_Basketball_Brand Under_Armour_篮球_品牌

Im attempting a market basket analysis and need to remove column names eventually.我正在尝试进行购物篮分析,最终需要删除列名。 However I will lose the information on what sport the brand belongs to without appending the column names to the observations themselves.但是,如果不将列名称附加到观察本身,我将丢失有关该品牌属于哪种运动的信息。 Essentially I wont be able to tell whether a 'nike' entry belongs to soccer or basketball.基本上我无法判断“耐克”条目是属于足球还是篮球。

I've used Excel formulas to hack a solution thus far but want my R script to be self contained.到目前为止,我已经使用 Excel 公式破解了一个解决方案,但希望我的 R 脚本是独立的。 I haven't found any solutions out there for this in R.我还没有在 R 中找到任何解决方案。

You can paste a column's name onto its contents.您可以将列的名称paste到其内容上。 Just iterate through all the columns.只需遍历所有列。 Doing so with lapply allows the one-liner:使用lapply这样做允许单行:

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

resulting in导致

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

Data from question in reproducible format问题数据以可重现的格式

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

Or using an option in tidyverse或者使用tidyverse中的一个选项

library(dplyr)
library(stringr)
df <- df %>% 
   mutate(across(everything(), ~ str_c(.x, cur_column(), sep = "_")))

-output -输出

df
         Soccer_Brand              Basketball_Brand
1 Adidas_Soccer_Brand         Nike_Basketball_Brand
2   Nike_Soccer_Brand Under Armour_Basketball_Brand

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM