我有 df ,其中包含一列地鐵線。問題是 L9N 和 L10N 有時出現在同一行,我想將它們分成兩個不同的行。我一直在嘗試很多事情,但我不知道該怎么做。
| 型別 | 線條 | 年 |
|---|---|---|
| 麥德龍 | L5 | 1959年 |
| 麥德龍 | L5 | 1959年 |
| 麥德龍 | L5 | 1959年 |
| 麥德龍 | L9NL10N | 2009 |
| 麥德龍 | L9S | 2016 年 |
| 麥德龍 | L10S | 2018 |
| 麥德龍 | L10N | 2010 |
| 麥德龍 | L4 | 1926年 |
| 麥德龍 | L1 | 1926年 |
| 麥德龍 | L1 | 1926年 |
uj5u.com熱心網友回復:
data.table單線。
它使用lookbehind-lookahead 正則運算式"(?<=\[NS])(?=L)"來識別分割點(在大寫N(或S)和大寫L之間),然后分割這些行,保留分隔符。
library(data.table)
setDT(mydata)[, .(Lines = unlist(tstrsplit(Lines, "(?<=[NS])(?=L)", perl = TRUE))), by = .(Type, Year)][]
# Type Year Lines
# 1: METRO 1959 L5
# 2: METRO 1959 L5
# 3: METRO 1959 L5
# 4: METRO 2009 L9N
# 5: METRO 2009 L10N
# 6: METRO 2016 L9S
# 7: METRO 2018 L10S
# 8: METRO 2010 L10N
# 9: METRO 1926 L4
#10: METRO 1926 L1
#11: METRO 1926 L1
編輯:在任何大寫字母之后
使用正則運算式"(?<=[A-Z])(?=L)"進行拆分[A-Z],然后是大寫字母L。
uj5u.com熱心網友回復:
這是data.frames的一種整潔有效的方法:
library(dplyr)
df %>%
mutate(Lines = stringr::str_extract_all(Lines, "L\\d*([NSEW]?)")) %>%
tidyr::unnest(Lines)
#> # A tibble: 11 × 3
#> Type Lines Year
#> <chr> <chr> <dbl>
#> 1 METRO L5 1959
#> 2 METRO L5 1959
#> 3 METRO L5 1959
#> 4 METRO L9N 2009
#> 5 METRO L10N 2009
#> 6 METRO L9S 2016
#> 7 METRO L10S 2018
#> 8 METRO L10N 2010
#> 9 METRO L4 1926
#> 10 METRO L1 1926
#> 11 METRO L1 1926
由reprex 包于 2022-04-01 創建(v2.0.1)
它適用于以下模式的任何重復行:L <som number> <possible one of N, S, E or W>.
資料
df <- tibble::tribble(
~Type, ~Lines, ~Year,
"METRO", "L5", 1959,
"METRO", "L5", 1959,
"METRO", "L5", 1959,
"METRO", "L9NL10N", 2009,
"METRO", "L9S", 2016,
"METRO", "L10S", 2018,
"METRO", "L10N", 2010,
"METRO", "L4", 1926,
"METRO", "L1", 1926,
"METRO", "L1", 1926
)
uj5u.com熱心網友回復:
另一種可能的解決方案:
library(tidyverse)
df %>%
separate_rows(Lines, sep="(?<=[N|S])(?=L)")
#> # A tibble: 11 × 3
#> Type Lines Year
#> <chr> <chr> <int>
#> 1 METRO L5 1959
#> 2 METRO L5 1959
#> 3 METRO L5 1959
#> 4 METRO L9N 2009
#> 5 METRO L10N 2009
#> 6 METRO L9S 2016
#> 7 METRO L10S 2018
#> 8 METRO L10N 2010
#> 9 METRO L4 1926
#> 10 METRO L1 1926
#> 11 METRO L1 1926
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/454427.html
