Мы могли бы gather
, а затем сделать spread
library(tidyverse)
df1 %>%
select(-tdid, -tiid) %>%
gather(key, val, tmid:thid) %>%
unite(keyn, key, mid, sep="") %>%
spread(keyn, val, fill = '0') %>%
right_join(df1) %>%
select(names(df1), everything(), -tdid, -tiid)
# A tibble: 13 x 14
# hid mid tmid thid thid1 thid2 thid3 thid4 thid5 tmid1 tmid2 tmid3
# <dbl> <dbl> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr>
# 1 1 1 010 010 010 02020 010 02020 0 010 01010 010
# 2 1 2 01010 02020 010 02020 010 02020 0 010 01010 010
# 3 1 3 010 010 010 02020 010 02020 0 010 01010 010
# 4 1 4 01020 02020 010 02020 010 02020 0 010 01010 010
# 5 2 1 010 000 000 0120 010 010 010 010 0120 010
# 6 2 2 0120 0120 000 0120 010 010 010 010 0120 010
# 7 2 3 010 010 000 0120 010 010 010 010 0120 010
# 8 2 4 010 010 000 0120 010 010 010 010 0120 010
# 9 2 5 020 010 000 0120 010 010 010 010 0120 010
#10 3 1 010 010 010 02020 010 02020 0 010 01010 010
#11 3 2 01010 02020 010 02020 010 02020 0 010 01010 010
#12 3 3 010 010 010 02020 010 02020 0 010 01010 010
#13 3 4 01020 02020 010 02020 010 02020 0 010 01010 010
# ... with 2 more variables: tmid4 <chr>, tmid5 <chr>
данных
df1 <- structure(list(hid = c(1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3),
mid = c(1, 2, 3, 4, 1, 2, 3, 4, 5, 1, 2, 3, 4), tmid = c("010",
"01010", "010", "01020", "010", "0120", "010", "010", "020",
"010", "01010", "010", "01020"), thid = c("010", "02020",
"010", "02020", "000", "0120", "010", "010", "010", "010",
"02020", "010", "02020"), tdid = c("000", "01010", "010",
"02020", "000", "0100", "010", "010", "010", "000", "01010",
"010", "02020"), tiid = c("010", "02020", "010", "01020",
"020", "0220", "020", "020", "020", "010", "02020", "010",
"01020")), .Names = c("hid", "mid", "tmid", "thid", "tdid",
"tiid"), row.names = c(NA, -13L), class = c("tbl_df", "tbl",
"data.frame"))