首页 > 解决方案 > 在特殊字符和 N 个附加字符后添加条件空格

问题描述

清理以下网络抓取的数据并在一致的位置获取没有适当间距的向量:

" SharePriceNAVPremium/Discount" "当前$21.26$20.901.72%" "52 周平均 $24.41$23.245.05%" "52 周高$28.00$25.0518.09%"
"52 周低$18.52$19.11-4.92%" ""

我试图让数据看起来像这样:

"SharePrice NAV 溢价/折扣" "当前 $21.26 $20.90 1.72%" "52WkAvg $24.41 $23.24 5.05%" "52WkHigh $28.00 $25.05 18.09%"
"52WkLow $18.52 $19.11 -4.92%"

我遇到的问题是如何在“$”加上 4 个数字后有条件地添加一个空格(因为这似乎是此处使用的一致价格约定)。

尝试过 str_pad 和 str_replace_all 没有普遍成功。任何帮助表示赞赏!

这是我的脚本:

library(rvest)
library(stringr)

CEF_Page <- read_html("https://www.cefconnect.com/fund/JLS")

test9 <- CEF_Page %>%
        html_nodes("#ContentPlaceHolder1_cph_main_cph_main_SummaryGrid") %>% 
        html_text() %>%
        strsplit(split = "\n") %>%
        unlist() %>%
        .[. != " "]


test9 <- str_replace_all(test9,pattern = "\t", replacement = "") 
test9 <- str_replace_all(test9,pattern = "\r", replacement = "")

标签: rdata-cleaningstringrstringi

解决方案


推荐阅读