我想将宽桌子重整为长桌子。我要收集的列具有模式。现在,我只设法按照他们的位置来收集他们。我如何更改此设置以通过列名称中的模式收集它们?请仅使用收集功能。
dput(head(test1, 1))
structure(list(startdate = "2019-11-06", id = "POL55", m0_9 = NA_real_,
m10_19 = NA_real_, m20_29 = NA_real_, m30_39 = NA_real_,
m40_49 = 32, m50_59 = NA_real_, m60_69 = NA_real_, m70 = NA_real_,
f0_9 = 32, f10_19 = NA_real_, f20_29 = NA_real_, f30_39 = NA_real_,
f40_49 = NA_real_, f50_59 = NA_real_, f60_69 = NA_real_,
f70 = NA_real_), row.names = c(NA, -1L), class = c("tbl_df",
"tbl", "data.frame"))
df_age2 <- test1 %>%
gather(age_bucket, count, m0_9:f70 )
df_age2
使用starts_with
:
test1 %>%
gather(age_bucket, count, c(starts_with("m"), starts_with("f")))
我们可以使用pivot_longer
中的tidyr
library(dplyr)
library(tidyr)
test1 %>%
pivot_longer(cols = -c(startdate, id), names_to = c('.value', 'grp'), names_sep="_")