【发布时间】:2021-03-17 19:41:40
【问题描述】:
我有一个这样的字符串。
"457, 1480-(5, 12), 83-(1, 2), 484, 484-(2, 3, 8)"
我只想在有括号的情况下为每个元素分配一个标题编号。 我想要的输出是这个
"457, 1480-5, 1480-12, 83-1, 83-2, 484, 484-2, 484-3, 484-8"
我该怎么做?
【问题讨论】:
我有一个这样的字符串。
"457, 1480-(5, 12), 83-(1, 2), 484, 484-(2, 3, 8)"
我只想在有括号的情况下为每个元素分配一个标题编号。 我想要的输出是这个
"457, 1480-5, 1480-12, 83-1, 83-2, 484, 484-2, 484-3, 484-8"
我该怎么做?
【问题讨论】:
我不确定我是否完全回答了这个问题,但我已将第一个列表更改为第二个列表(在数据框中)。
library(tidyverse)
library(stringi)
df <- tibble::tribble(
~column,
"457, 480-(5, 12), 483-(1, 2), 484, 484-(2, 3, 8)"
)
以下使用逗号作为分隔符分隔部分,删除括号,然后我使用 {stringi} 重新格式化数字。我创建了 2 个额外的列,一个用于主要的 3 位数字(main_number),一个用于子集号(用 - 表示)。重新格式化后,如果没有子集,我将使用 main_number,其余部分粘贴 main_number 和子集这两列。
df2 <- df %>%
mutate(split_out = strsplit(as.character(column), ",")) %>%
tidyr::unnest(split_out) %>%
select(-column) %>%
mutate(split_out = str_remove(split_out, "[()]"),
split_out = str_trim(split_out), # has trailing whitespace
main_number = case_when(stri_length(split_out) == 3 ~ split_out,
TRUE ~ substr(split_out, 1, str_locate(split_out, "-") -1)),
subset = case_when(str_detect(split_out, "-") == TRUE ~ substr(split_out,
str_locate(split_out, "-"), # where - appears + 1
stri_length(split_out)), # the end of the string
stri_length(split_out) < 3 ~ paste0("-", split_out),
TRUE ~ NA_character_)) %>%
fill(main_number, .direction = c("down")) %>% # fill down so the main number is copied down
mutate(new_number = case_when(is.na(subset) ~ main_number,
TRUE ~ paste0(main_number, subset)
)) %>%
select(new_number)
【讨论】: