Мы можем использовать melt
из data.table
и paste
элементов вместе
library(data.table)
melt(setDT(df1, keep.rownames = TRUE), measure =
patterns('^test', 'type', 'other'),
value.name = c('test', 'type', 'other'))[,
variable := NULL][, lapply(.SD, paste, collapse=""),
.(rn)][, rn := NULL][]
# test type other
#1: aff dst jyb
#2: sdc vsy ham
#3: dsv dhu njk
Или с помощью аналогичного метода в tidyverse
library(dplyr)
library(tidyr)
library(stringr)
df1 %>%
mutate(rn = row_number()) %>%
pivot_longer(cols = -rn, names_to = c( ".value", 'grp'), names_sep="_") %>%
group_by(rn) %>%
summarise_at(vars(test:other), str_c, collapse ="") %>%
select(-rn)
# A tibble: 3 x 3
# test type other
# <chr> <chr> <chr>
#1 aff dst jyb
#2 sdc vsy ham
#3 dsv dhu njk
data
df1 <- structure(list(test_1 = c("a", "s", "d"), test_2 = c("f", "d",
"s"), test_3 = c("f", "c", "v"), type_1 = c("d", "v", "d"), type_2 = c("s",
"s", "h"), type_3 = c("t", "y", "u"), other_1 = c("j", "h", "n"
), other_2 = c("y", "a", "j"), other_3 = c("b", "m", "k")),
class = "data.frame", row.names = c(NA,
-3L))