从两列中提取数据

时间:2019-07-02 08:22:53

标签: r subset

我有一个看起来像这样的数据框。 它指的是单词及其结构

df <- data.frame(word = c("pokkoitta", "demna", "ningatinggo ", "tengkeam", "bampana", "njam"), structure = c("CvC:vvC:v", "CvCCv", "CvCvCvNCv", "CvNCvvC", "CvNCvCv" , "NCvC"))

第二列指示第一列的结构。如果在第二列中出现C:,NC或CC组合,则需要从第一列中提取这些内容。

所以我需要:

kk C: kk C: mn CC ngg NC ngk NC mp NC nj NC 需要考虑的一件事是,对左列中的2个字母(对应于右列中的1个字母),简单计数不起作用,即ng | sy | kh = C(不是CC,因为它们表示一个音素) 而且,总而言之,这些组合中可能有不止一种

Thx

更新:

这将是与正则表达式匹配的模式:

(nj|ngk|ngg|nc|nt|nd|mp|mb) = NC
(ng|sy|kh) = C    
[b-df-hj-np-tv-xz])\\1+) = C:
([b-df-hj-np-tv-z]) = C
(') = :    
((a|e|i|o|u)\\1+) = v:    
(a|e|i|o|u)  = v     

1 个答案:

答案 0 :(得分:0)

有趣的问题。我可能刚刚重新发明了用于查找那些结构的算法,但它似乎可以工作。

df <- data.frame(
  word=c("pokkoitta", "demna", "ningatinggo", "tengkeam", "bampana", "njam"),
  structure=c("CvC:vvC:v", "CvCCv", "CvCvCvNCv", "CvNCvvC", "CvNCvCv", "NCvC"),
  stringsAsFactors=FALSE)

pat <- data.frame(str=c("NC", "C", "C:", "C", "v:", "v"),
                  rex=c("nj|ngk|ngg|nc|nt|nd|mp|mb",
                        "ng|sy|kh",
                        "([b-df-hj-np-tv-xz])\\1+",
                        "[b-df-hj-np-tv-z]",
                        "(a|e|i|o|u)\\1+",
                        "a|e|i|o|u"), stringsAsFactors=FALSE)

xs <- xw <- df[,1]
for (i in 1:nrow(pat)) {
    rx <- gregexpr(pat[i, 2], xs)
    mc <- regmatches(xs, rx)
    mp <- sapply(mc, function(x) format(paste("", x), width=6))
    mc[lengths(mc) != 0] <- mp[lengths(mc) != 0]
    regmatches(xw, rx) <- mc
    regmatches(xs, rx) <- paste("", format(pat[i, 1], width=5))
}

phon <- trimws(cbind(word=xw, structure=xs))
phon <- apply(phon, 1, strsplit, " +")
phon <- lapply(phon, function(x) do.call(cbind, x))
head(phon, 3)
# [[1]]
#      word structure
# [1,] "p"  "C"      
# [2,] "o"  "v"      
# [3,] "kk" "C:"     
# [4,] "o"  "v"      
# [5,] "i"  "v"      
# [6,] "tt" "C:"     
# [7,] "a"  "v"      
# 
# [[2]]
#      word structure
# [1,] "d"  "C"      
# [2,] "e"  "v"      
# [3,] "m"  "C"      
# [4,] "n"  "C"      
# [5,] "a"  "v"      
# 
# [[3]]
#      word  structure
# [1,] "n"   "C"      
# [2,] "i"   "v"      
# [3,] "ng"  "C"      
# [4,] "a"   "v"      
# [5,] "t"   "C"      
# [6,] "i"   "v"      
# [7,] "ngg" "NC"     
# [8,] "o"   "v"