在 R 中包含数字和文本不等量混合的单独列
Separate columns that contain an unequal mixture of numbers and text in R
我有一个非常奇怪的数据框,看起来像这样
library(tidyverse)
df <- tibble(position=c(100,200,300),
correction=c("62M89S",
"8M1D55M88S",
"1S25M1P36M89S"))
df
#> # A tibble: 3 × 2
#> position correction
#> <dbl> <chr>
#> 1 100 62M89S
#> 2 200 8M1D55M88S
#> 3 300 1S25M1P36M89S
由 reprex package (v2.0.1) 创建于 2022-03-02
更正栏将用于更正位置。
我想以我的数据框看起来像这样的方式分隔校正列
df col1 col2 col3 col4 col5
100 62M 89S
200 8M 1D 55M 88S
300 1S 25M 1P 36M 89S
将 tidyr::separate
与 fill = "left"
一起使用:
library(tidyr)
library(dplyr)
df %>%
separate(correction, into = str_c("col", 1:5),
sep = "(?<=\D)(?=\d)", fill = "left")
# A tibble: 3 x 6
position col1 col2 col3 col4 col5
<dbl> <chr> <chr> <chr> <chr> <chr>
1 100 NA NA NA 62M 89S
2 200 NA 8M 1D 55M 88S
3 300 1S 25M 1P 36M 89S
我有一个非常奇怪的数据框,看起来像这样
library(tidyverse)
df <- tibble(position=c(100,200,300),
correction=c("62M89S",
"8M1D55M88S",
"1S25M1P36M89S"))
df
#> # A tibble: 3 × 2
#> position correction
#> <dbl> <chr>
#> 1 100 62M89S
#> 2 200 8M1D55M88S
#> 3 300 1S25M1P36M89S
由 reprex package (v2.0.1) 创建于 2022-03-02 更正栏将用于更正位置。 我想以我的数据框看起来像这样的方式分隔校正列
df col1 col2 col3 col4 col5
100 62M 89S
200 8M 1D 55M 88S
300 1S 25M 1P 36M 89S
将 tidyr::separate
与 fill = "left"
一起使用:
library(tidyr)
library(dplyr)
df %>%
separate(correction, into = str_c("col", 1:5),
sep = "(?<=\D)(?=\d)", fill = "left")
# A tibble: 3 x 6
position col1 col2 col3 col4 col5
<dbl> <chr> <chr> <chr> <chr> <chr>
1 100 NA NA NA 62M 89S
2 200 NA 8M 1D 55M 88S
3 300 1S 25M 1P 36M 89S