![](/img/trans.png)
[英]Is there a way to append to each vector element with the respective name of list element?
[英]Is there a way to append a column name to the end of each observation within respective columns?
[R] 我正在尝试修改我的数据框 (df) 的格式,以便将列名称附加到 R 内该列中的每个观察值。例如:
足球品牌 | 篮球_品牌 |
---|---|
阿迪达斯 | 耐克 |
耐克 | 安德玛 |
并想让它看起来像
足球品牌 | 篮球_品牌 |
---|---|
阿迪达斯足球品牌 | 耐克_篮球_品牌 |
耐克_足球_品牌 | Under_Armour_篮球_品牌 |
我正在尝试进行购物篮分析,最终需要删除列名。 但是,如果不将列名称附加到观察本身,我将丢失有关该品牌属于哪种运动的信息。 基本上我无法判断“耐克”条目是属于足球还是篮球。
到目前为止,我已经使用 Excel 公式破解了一个解决方案,但希望我的 R 脚本是独立的。 我还没有在 R 中找到任何解决方案。
您可以将列的名称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"))
或者使用tidyverse
中的一个选项
library(dplyr)
library(stringr)
df <- df %>%
mutate(across(everything(), ~ str_c(.x, cur_column(), sep = "_")))
-输出
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.