strsplit与非字符数据

时间:2015-05-27 00:05:41

标签: r reshape reshape2 strsplit agrep

1我想对一个变量ID1执行strsplit以分割成ID1_s1和ID1_s2,我需要删除括号中的字符串。

#  dummy data
df1 <- data.frame(ID1=c("Gindalinc","Xaviertechnolgies","anine.inc(Nasq)","Xyzinc"), y=1:4)
strsplit(df1$ID1, "\\(")

如何将strplit分成ID1_s1和ID_s2&#34;(&#34;括号?

我需要输出如下:

 ID1_s1                ID1_s2      y
 Gindalinc                        1
 Xaviertechnolgies                2
 anine.inc             (Nasq)     3
 Xyzinc                           4

3 个答案:

答案 0 :(得分:1)

在定义数据框时使用stringsAsFactors = FALSE(或者如果已存在,请使用df1 <- transform(df1, ID1 = as.character(df1))并使用strsplit指示的模式。

df1 <- data.frame(ID1 = c("Gindalinc","Xaviertechnolgies","anine.inc(Nasq)","Xyzinc"), 
                  y = 1:4, stringsAsFactors = FALSE)
s <- strsplit(df1$ID1, "[()]")

,并提供:

> s
[[1]]
[1] "Gindalinc"

[[2]]
[1] "Xaviertechnolgies"

[[3]]
[1] "anine.inc" "Nasq"     

[[4]]
[1] "Xyzinc"
问题更新后

已添加以包含所需的输出。使用gsubfn包中的read.pattern分割字段,如下所示:

library(gsubfn)

cn <- c("ID1_s1", "ID1_s2")
with(df1, data.frame(read.pattern(text = ID1, pattern = "([^(]*)(.*)", col.names = cn), y))

giving:

             ID1_s1 ID1_s2 y
1         Gindalinc        1
2 Xaviertechnolgies        2
3         anine.inc (Nasq) 3
4            Xyzinc        4

已添加如果输出中出现括号并不重要,那么另一个解决方案是(使用上面代码中的s):

data.frame(ID1_s1 = sapply(s, "[", 1), ID1_s2 = sapply(s, "[", 2), y = df1$y)

,并提供:

             ID1_s1 ID1_s2 y
1         Gindalinc   <NA> 1
2 Xaviertechnolgies   <NA> 2
3         anine.inc   Nasq 3
4            Xyzinc   <NA> 4

答案 1 :(得分:1)

library("tidyr")

df1 <- data.frame(ID1=c("Gindalinc","Xaviertechnolgies","anine.inc(Nasq)","Xyzinc"), y=1:4)

df2 <- separate(df1 , ID1 ,c("ID1_s1" , "ID1_s2") , sep = "(?=\\()" , extra = "drop")

#     ID1_s1           ID1_s2  y
# 1  Gindalinc          <NA>   1
# 2 Xaviertechnolgies   <NA>   2
# 3 anine.inc          (Nasq)  3
# 4 Xyzinc              <NA>   4

# if you want to convert na to ""
df2$ID1_s2[is.na(df2$ID1_s2)] <- ""

#         ID1_s1      ID1_s2 y
# 1         Gindalinc        1
# 2 Xaviertechnolgies        2
# 3         anine.inc (Nasq) 3
# 4            Xyzinc        4

答案 2 :(得分:0)

晚安,使用虚拟数据和之前给出的建议,我已准备好(并测试)下面的代码以产生预期结果。

我希望它可以帮助您处理数据。

# creating an inicial dataframe
df1 <- data.frame(ID1 = c("Gindalinc","Xaviertechnolgies","anine.inc(Nasq)","Xyzinc"), 
                  y = 1:4, stringsAsFactors = FALSE)

# spliting the element with parenthesis/brackets
y = strsplit(df1$ID1, "[()]")
y

# recreating the parentesis (if needed)
y[[3]][2] = "(Nasq)" 

z = c() # creating null vector for loop

# taking the first element from the list and converting it to a column
for (i in 1:4)  
    z = rbind(z,y[[i]][1])

z2 = c() # creating null vector for loop
# taking the second element from the list and converting it to a column
for (i in 1:4)
    z2 = rbind(z2,y[[i]][2])

# recreating the dataframe in the expected way
df1 = data.frame(ID1_s1 = z,ID1_s2 = z2,y = df1$y)
df1