我敢肯定標題可以措辭更好,但基本上我有以下資料:
location group financial_year h0to2 h10plus h2to4 h4to10 total perc0to2 perc2to4 perc4to10
<chr> <chr> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
6 partnership x 2020/21 0 5 5 15 25 0 20 60
我想創建一個新列“level_of_service”,其中包含行“a0to2”、“a2to4”、“a4to10”、“a10 ”,其中“Value”列從以 h 開頭的列和列中獲取值“百分比”從 perc 列中獲取值。
將以下代碼與 pivot_longer 一起使用:
mydata2 <- mydata %>%
pivot_longer(cols = c("h0to2", "h2to4", "h4to10", "h10plus", "perc0to2", "perc2to4", "perc4to10", "perc10plus"),
names_to = "level_of_service"
)
我得到以下資料:
location group financial_year total level_of_service value
<chr> <chr> <chr> <dbl> <chr> <dbl>
1 partnership x 2020/21 0 h0to2 0
2 partnership x 2020/21 0 perc0to2 0
我想要這個,但有 2 個值列,一個用于 h0to2 行,另一個用于 perc0to2 行。
對不起,如果這很長,我已經有一段時間沒有使用 stackoverflow 提出問題了!任何幫助將不勝感激。
uj5u.com熱心網友回復:
使用特殊".value"的和names_pattern你可以做的論點:
library(tidyr)
mydata %>%
pivot_longer(
cols = matches("^(h|p)"),
names_to = c(".value", "level_of_service"),
names_pattern = "^(h|perc)(.*)$"
)
#> # A tibble: 4 × 7
#> location group financial_year total level_of_service h perc
#> <chr> <chr> <chr> <int> <chr> <int> <int>
#> 1 partnership x 2020/21 25 0to2 0 0
#> 2 partnership x 2020/21 25 10plus 5 NA
#> 3 partnership x 2020/21 25 2to4 5 20
#> 4 partnership x 2020/21 25 4to10 15 60
資料
mydata <- read.table(text = "location group financial_year h0to2 h10plus h2to4 h4to10 total perc0to2 perc2to4 perc4to10
6 partnership x 2020/21 0 5 5 15 25 0 20 60 ", header = TRUE)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/527694.html
標籤:r枢多列蒂迪尔
上一篇:Dplyr遞回地增長資料框
下一篇:分箱和計數成向量
