拆分后如何将两个元素放入R中的新两个字符串向量中

时间:2019-03-01 23:14:28

标签: r

我已经用

分割了字符串向量
var1=strsplit(USYTDsales, split = "\\(")
var1

并得到类似

的结果
[[1]]
[1] "160,397 " "-0.9%)"  

[[2]]
[1] "52,296 " "+27.6%)"

[[3]]
[1] "399,337 " "+5.2%)"  

[[4]]
[1] "58,167 " "-10.8%)"

[[5]]
[1] "1,286,524 " "+5.9%)"    

[[6]]
[1] "124,577 " "+3.7%)"  

[[7]]
[1] "840,256 " "-1.7%)"  

[[8]]
[1] "199,997 " "-13.4%)" 

[[9]]
[1] "75,949 " "+5.4%)" 

[[10]]
[1] "175,368 " "+2.5%)"  

[[11]]
[1] "203,407 " "+8.0%)"  

[[12]]
[1] "85,900 " "-2.4%)" 

[[13]]
[1] "26,932 " "+1.3%)" 

[[14]]
[1] "305,406 " "-5.7%)"  

[[15]]
[1] "269,507 "    "+2.4%) "     "through Q2)"

[[16]]
[1] "378,922 " "-2.6%)"  

[[17]]
[1] "188,049 " "+11.5%)" 

[[18]]
[1] "574,928 " "+20.9%)" 

[[19]]
[1] "109,695 "    "-0.6%) "     "through Q2)"

[[20]]
[1] "807,570 " "-5.9%)"  

[[21]]
[1] "346,675 " "-1.6%)"  

[[22]]
[1] "1,019,019 "  "+5.2%) "     "through Q2)"

[[23]]
[1] "77,277 " "+23.4%)"

[[24]]
[1] "81,917 " "-9.0%)" 

[[25]]
[1] "9,525 "  "-43.7%)"

[[26]]
[1] "1,411,243 " "-1.5%)"    

[[27]]
[1] "282,052 " "-3.5%)"  

[[28]]
[1] "100,254 " "-13.1%)" 

现在我想将分割的第一部分放入一个向量,并将分割的第二部分放入另一个向量。

1 个答案:

答案 0 :(得分:1)

假设输入x在下面的注释中可重复显示,请删除垃圾字符并使用read.table读取字符串:

read.table(text = gsub("[,+%)]", "", x), sep = "(", strip.white = TRUE, 
   col.names = c("A", "B"))

给予:

       A    B
1 123456 -0.9
2 987456  1.0

注意

x <- c("123,456 (-0.9%)", "987,456 (1.0%)")