[英]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 ![]() |
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.