我有一个像这样的小标题/数据框:
hc_inpatient_sum hc_ambulant_sum hc_inpatient_mean hc_ambulant_mean
5 2 5.5 2.2
我想要的输出是:
my_names sum mean
hc_inpatient 5 5.5
hc_ambulant 2 2.2
使用以下代码,我得到了想要的东西。但是,这似乎很复杂。我想使用较少复杂的代码也可以获得相同的结果。
library(dplyr)
library(tidyr)
my_data <- tibble(hc_inpatient_sum = 5, hc_ambulant_sum = 2, hc_inpatient_mean = 5.5,
hc_ambulant_mean = 2.2)
res <- my_data %>%
pivot_longer(cols = everything(), names_to = "my_names", values_to = "my_values") %>%
separate(my_names, into = c("my_names", "stats"), sep = "_(?=[^_]+$)") %>%
pivot_wider(names_from = "stats", values_from = "my_values")
使用tidyr :: pivot_longer是否有更直接的方法来获得相同的结果?
或者我可以做这样的事情...
res2 <- pivot_longer(my_data, cols = everything(),
names_to = c(".value", "stats"),
names_pattern = "(.*)_(.*)") %>%
t()
colnames(res2) <- res2["stats",]
res2 <- as_tibble(res2[-1,], rownames = "my_names") %>%
mutate_at(vars(-my_names), as.double)
...但是那更尴尬。
答案 0 :(得分:1)
您可以与...合而为一。
df %>% pivot_longer(everything(),
names_to = c("my_names", ".value"),
names_pattern = "(.+)_(.+$)")
my_names sum mean
<chr> <int> <dbl>
1 hc_inpatient 5 5.5
2 hc_ambulant 2 2.2
这些示例对于解决pivot_longer
https://tidyr.tidyverse.org/reference/pivot_longer.html