我有一个 tibble/dataframe ,如下所示:
hc_inpatient_sum hc_ambulant_sum hc_inpatient_mean hc_ambulant_mean
5 2 5.5 2.2
Run Code Online (Sandbox Code Playgroud)
我想要的输出是:
my_names sum mean
hc_inpatient 5 5.5
hc_ambulant 2 2.2
Run Code Online (Sandbox Code Playgroud)
我使用以下代码得到了我想要的。然而,这似乎相当复杂。我猜想使用不太复杂的代码可以获得相同的结果。
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")
Run Code Online (Sandbox Code Playgroud)
有没有更直接的方法使用 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)
Run Code Online (Sandbox Code Playgroud)
……不过这样就更尴尬了。
您可以与...合而为一地完成此操作
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
Run Code Online (Sandbox Code Playgroud)
这些示例对于掌握pivot_longer https://tidyr.tidyverse.org/reference/pivot_longer.html的窍门非常有帮助