Мы можем gather
перевести в «длинный» формат, а затем spread
вернуть его в «широкий» формат после создания столбца последовательности по группе
library(tidyverse)
df1 %>%
gather(key, val, height:weight) %>%
group_by(sample, key) %>%
mutate(n = row_number()) %>%
unite(keyn, key, n, sep="") %>%
spread(keyn, val)
# A tibble: 2 x 7
# Groups: sample [2]
# sample height1 height2 weight1 weight2 width1 width2
# <chr> <chr> <chr> <chr> <chr> <chr> <chr>
#1 a h1 h2 p1 p2 w1 w2
#2 b h3 h4 p3 p4 w3 w4
Или другой вариант с tidyverse
df1 %>%
group_by(sample) %>%
nest %>%
mutate(data = map(data, ~
unlist(.x) %>%
as.list %>%
as_tibble)) %>%
unnest
Или мы можем использовать reshape
из base R
df1$ind <- with(df1, ave(seq_along(sample), sample, FUN = seq_along))
reshape(df1, idvar= c("sample"), timevar = "ind", direction = "wide")
# sample height.1 width.1 weight.1 height.2 width.2 weight.2
#1 a h1 w1 p1 h2 w2 p2
#3 b h3 w3 p3 h4 w4 p4
данные
df1 <- structure(list(sample = c("a", "a", "b", "b"), height = c("h1",
"h2", "h3", "h4"), width = c("w1", "w2", "w3", "w4"), weight = c("p1",
"p2", "p3", "p4")), class = "data.frame", row.names = c(NA, -4L
))