尝试按照 str_split_n() 的方式拆分字符串,但无法调用它,尽管它在 stringr 的手册和 repo 中
Trying to split strings the way str_split_n() does, but cannot call it although it is in stringr's manual and repo
如何在此处拆分字符串?由于某些原因 str_split_n
在 stringr
的仓库中,但无法使用它。也没有帮助文件。
所以我想用这个:
x <- c("a", "b[12]", "c[34]", "d")
tibble(x) |>
dplyr::mutate(
y = str_split_n(x, "\[", 1)
)
得到这个:
# A tibble: 4 x 2
x y
<chr> <chr>
1 a a
2 b[12] b
3 c[34] c
4 d d
我们可以在这里使用 sub
,并删除尾部括号中的项目:
df <- data.frame(x=c("a", "b[12]", "c[34]", "d"))
df$y <- sub("\[.*?\]$", "", df$x)
df
x y
1 a a
2 b[12] b
3 c[34] c
4 d d
我想你要找的是 -
tibble(x) |>
dplyr::mutate(
y = stringr::str_split_fixed(x, "\[", 2)[, 1]
)
# x y
# <chr> <chr>
#1 a a
#2 b[12] b
#3 c[34] c
#4 d d
使用 base R
中的 trimws
df$x <- trimws(df$x, whitespace = "\[.*")
df$x
[1] "a" "b" "c" "d"
数据
df <- data.frame(x=c("a", "b[12]", "c[34]", "d"))
如何在此处拆分字符串?由于某些原因 str_split_n
在 stringr
的仓库中,但无法使用它。也没有帮助文件。
所以我想用这个:
x <- c("a", "b[12]", "c[34]", "d")
tibble(x) |>
dplyr::mutate(
y = str_split_n(x, "\[", 1)
)
得到这个:
# A tibble: 4 x 2
x y
<chr> <chr>
1 a a
2 b[12] b
3 c[34] c
4 d d
我们可以在这里使用 sub
,并删除尾部括号中的项目:
df <- data.frame(x=c("a", "b[12]", "c[34]", "d"))
df$y <- sub("\[.*?\]$", "", df$x)
df
x y
1 a a
2 b[12] b
3 c[34] c
4 d d
我想你要找的是 -
tibble(x) |>
dplyr::mutate(
y = stringr::str_split_fixed(x, "\[", 2)[, 1]
)
# x y
# <chr> <chr>
#1 a a
#2 b[12] b
#3 c[34] c
#4 d d
使用 base R
trimws
df$x <- trimws(df$x, whitespace = "\[.*")
df$x
[1] "a" "b" "c" "d"
数据
df <- data.frame(x=c("a", "b[12]", "c[34]", "d"))