有什么办法可以将字符串拆分为R中的行吗?

时间:2019-12-19 07:25:08

标签: r

我有以下字符串“ [时间]。[会计年度]。&[2014]} ^ [时间]。[会计半年] ^ [时间]。[会计季度] ^ [时间]。[月]”并且需要以以下格式拆分字符串。请帮助我找到满足我要求的方法。

Column values must be as per image

3 个答案:

答案 0 :(得分:2)

您可以使用strsplit分割^,然后使用gsub查找模式[*].[*]并将结果放入data.frame

data.frame("Time Value"=
 gsub("(\\[.*?\\]\\.\\[.*?\\]).*", "\\1", strsplit(x,"\\^")[[1]])
 , check.names = FALSE)
#                 Time Value
#1      [Time].[Fiscal Year]
#2 [Time].[Fiscal Half Year]
#3   [Time].[Fiscal Quarter]
#4            [Time].[Month]

数据:

x <- "[Time].[Fiscal Year].&[2014]}^[Time].[Fiscal Half Year]^[Time].[Fiscal Quarter]^[Time].[Month]"

答案 1 :(得分:0)

也许代码可以满足您的需求。给定字符串s如下

s <- "[Time].[Fiscal Year].&[2014]}^[Time].[Fiscal Half Year]^[Time].[Fiscal Quarter]^[Time].[Month]"

然后可以通过

形成数据帧
r <- unlist(strsplit(s,"\\^"))
df <- data.frame("Time Value" = unlist(regmatches(r,gregexpr("\\[.*?\\]\\.\\[.*?\\]",r))),check.names = F)

如此

> df
                 Time Value
1      [Time].[Fiscal Year]
2 [Time].[Fiscal Half Year]
3   [Time].[Fiscal Quarter]
4            [Time].[Month]

答案 2 :(得分:0)

简单的Base R解决方案:

gsub( "\\.\\&.*", "", unlist(strsplit(x, "\\^")))

数据:

x <- "[Time].[Fiscal Year].&[2014]}^[Time].[Fiscal Half Year]^[Time].[Fiscal Quarter]^[Time].[Month]"