将文本拆分为字符和数字

时间:2018-03-01 22:21:09

标签: r stringr readr

有人可以帮我分割这个字符串:

string <- "Rolling in the deep    $15.25"

我正试图从中获得两个输出:

1) Rolling in the Deep  # character
2) 15.25                # numeric value

我知道如何在excel中执行此操作,但R

有点丢失

2 个答案:

答案 0 :(得分:1)

使用strsplit可以解决问题。解决方案如下:

string <- "Rolling in the deep    $15.25"

strsplit(string, "\\s+\\$")
                    ^   ^___ find a $ (escaped with \\ because $ means end of word)
                     \______ find 1 or more whitespaces
# Result
#"Rolling in the deep" "15.25"

strsplit(string, "\\s+\\$")[[1]][1]
#[1] "Rolling in the deep"

strsplit(string, "\\s+\\$")[[1]][2]
#[1] "15.25"

答案 1 :(得分:1)

只要右手边总是以美元符号开头,你就需要&#34;逃避&#34;美元符号。试试这个:

# you will need stringr, which you could load alone but the tidyverse is amazing
library(tidyverse)
string <- "Rolling in the deep    $15.25"
str_split_fixed(string, "\\$", n = 2)