[英]How do I convert/reshape a data frame in long format to a wide format without aggregating the records?
[英]How do I reshape a data.frame to long format with multiple value cols using regex expression
如何將 data.frame input
重塑為result
? 基本上, "dosis"
名的第一部分應該是具有兩個值列value
和dosis
的新變量,其中包含以/不以"dosis"
結尾的列的數據。
這應該不會太難,但我很難找到與pivot_longer
或melt.data.table
一起使用的正確正則表達式。
library(tibble)
library(tidyr)
library(magrittr)
library(data.table)
input <-
tribble(
~"abc", ~"abcdosis", ~"def", ~"defdosis", ~"ghi", ~"ghidosis",
1, 0, 9, NA, 1, 2
)
result <-
tribble(
~"variable", ~"value", ~"dosis",
"abc", 1, 0,
"def", 9, NA,
"ghi", 1, 2
)
# Not working
pivot_longer(input,
everything(),
names_to = c("variable", "dosis"),
names_pattern = "(^dosis)?(dosis)")
# Also not working
melt.data.table(as.data.table(input), measure.vars = patterns("^(?!.*dosis).*$", "dosis$"))
使用dplyr::rename_with()
您可以將"value"
粘貼到非"dosis"
列的末尾,然后在pivot_longer()
中使用".value"
標記。 當然,如果您的數據更復雜,可能必須更具體地使用rename_with()
中的列。
library(dplyr)
library(tidyr)
input %>%
rename_with(~paste0(., "value"), -ends_with("dosis")) %>%
pivot_longer(everything(), names_to = c("variable", ".value"), names_pattern = "(.*?)(value|dosis)$")
# A tibble: 3 x 3
variable value dosis
<chr> <dbl> <dbl>
1 abc 1 0
2 def 9 NA
3 ghi 1 2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.