只需添加两个选项 - 使用 stringr::str_split() 或 data.table::tstrsplit()
1) 使用stringr::str_split()
# data posted above by the asker
tmp3 <- c("1500 2", "1500 1", "1510 2", "1510 1", "1520 2", "1520 1", "1530 2",
"1530 1", "1540 2", "1540 1")
library(stringr)
as.integer(
str_split(string = tmp3,
pattern = "[[:space:]]",
simplify = TRUE)[, 2]
)
#> [1] 2 1 2 1 2 1 2 1 2 1
simplify = TRUE 告诉str_split 返回一个矩阵,然后我们可以为所需列索引矩阵,因此,[, 2] 部分
2) 使用data.table::tstrsplit()
library(data.table)
as.data.table(tmp3)[, tstrsplit(tmp3, split = "[[:space:]]", type.convert = TRUE)][, V2]
#> [1] 2 1 2 1 2 1 2 1 2 1
type.convert = TRUE 负责此处转换为整数,但请谨慎使用其他数据集。
索引[, V2] 部分的原因与上面对[, 2] 的解释类似。在这里,它选择返回的数据表对象的第二列,其中包含询问者所需的整数值。
sessionInfo()
#> R version 4.0.0 (2020-04-24)
#> Platform: x86_64-w64-mingw32/x64 (64-bit)
#> Running under: Windows 10 x64 (build 18362)
#>
#> Matrix products: default
#>
#> locale:
#> [1] LC_COLLATE=English_United States.1252
#> [2] LC_CTYPE=English_United States.1252
#> [3] LC_MONETARY=English_United States.1252
#> [4] LC_NUMERIC=C
#> [5] LC_TIME=English_United States.1252
#>
#> attached base packages:
#> [1] stats graphics grDevices utils datasets methods base
#>
#> loaded via a namespace (and not attached):
#> [1] compiler_4.0.0 magrittr_1.5 tools_4.0.0 htmltools_0.4.0
#> [5] yaml_2.2.1 Rcpp_1.0.4.6 stringi_1.4.6 rmarkdown_2.1
#> [9] highr_0.8 knitr_1.28 stringr_1.4.0 xfun_0.13
#> [13] digest_0.6.25 rlang_0.4.6 evaluate_0.14
由reprex package (v0.3.0) 于 2020 年 5 月 6 日创建