将列名附加到值的开头,并用下划线分隔
Append column name to the beginning of values separated by an underscore
如何将列名附加到列中每个值的开头,用“_”分隔,跳过第一列(或者,等效地,选择第二和第三列)?
multiple=data.frame(id=c(1:6),
status=c("good", "bad", "ok", "ok", "good", "bad"),
breakfast=c("eggs", "sausage", "eggs", "sausage", "sausage", "eggs"))
# Desired:
#id status breakfast
#1 status_good breakfast_eggs
#2 status_bad breakfast_sausage
#3 status_ok breakfast_eggs
#4 status_ok breakfast_sausage
#5 status_good breakfast_sausage
#6 status_bad breakfast_eggs
这是一个带有 tidyverse
的选项,我们循环 across
列并粘贴相应的列名 (cur_column()
)
library(dplyr)
library(stringr)
multiple %>%
mutate(across(c(status, breakfast), ~ str_c(cur_column(), "_", .)))
-输出
# id status breakfast
#1 1 status_good breakfast_eggs
#2 2 status_bad breakfast_sausage
#3 3 status_ok breakfast_eggs
#4 4 status_ok breakfast_sausage
#5 5 status_good breakfast_sausage
#6 6 status_bad breakfast_eggs
在 base R 中,我们可以使用 Map
:
multiple[-1] <- Map(function(x, y) paste(x, y, sep = '_'),
names(multiple)[-1], multiple[-1])
或 purrr
的 imap_dfc
:
multiple[-1] <- purrr::imap_dfc(multiple[-1], ~paste(.y, .x, sep = '_'))
multiple
# id status breakfast
#1 1 status_good breakfast_eggs
#2 2 status_bad breakfast_sausage
#3 3 status_ok breakfast_eggs
#4 4 status_ok breakfast_sausage
#5 5 status_good breakfast_sausage
#6 6 status_bad breakfast_eggs
如何将列名附加到列中每个值的开头,用“_”分隔,跳过第一列(或者,等效地,选择第二和第三列)?
multiple=data.frame(id=c(1:6),
status=c("good", "bad", "ok", "ok", "good", "bad"),
breakfast=c("eggs", "sausage", "eggs", "sausage", "sausage", "eggs"))
# Desired:
#id status breakfast
#1 status_good breakfast_eggs
#2 status_bad breakfast_sausage
#3 status_ok breakfast_eggs
#4 status_ok breakfast_sausage
#5 status_good breakfast_sausage
#6 status_bad breakfast_eggs
这是一个带有 tidyverse
的选项,我们循环 across
列并粘贴相应的列名 (cur_column()
)
library(dplyr)
library(stringr)
multiple %>%
mutate(across(c(status, breakfast), ~ str_c(cur_column(), "_", .)))
-输出
# id status breakfast
#1 1 status_good breakfast_eggs
#2 2 status_bad breakfast_sausage
#3 3 status_ok breakfast_eggs
#4 4 status_ok breakfast_sausage
#5 5 status_good breakfast_sausage
#6 6 status_bad breakfast_eggs
在 base R 中,我们可以使用 Map
:
multiple[-1] <- Map(function(x, y) paste(x, y, sep = '_'),
names(multiple)[-1], multiple[-1])
或 purrr
的 imap_dfc
:
multiple[-1] <- purrr::imap_dfc(multiple[-1], ~paste(.y, .x, sep = '_'))
multiple
# id status breakfast
#1 1 status_good breakfast_eggs
#2 2 status_bad breakfast_sausage
#3 3 status_ok breakfast_eggs
#4 4 status_ok breakfast_sausage
#5 5 status_good breakfast_sausage
#6 6 status_bad breakfast_eggs