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