两个几乎相同的R函数出错 - 一个被执行而另一个被执行

时间:2015-10-12 06:46:51

标签: r list function

我写过2个R函数,几乎完全相同。

extract_verb<-function(list1){
    sd<-names(list1)
    ds<-which(sd %in% "VP")
    if(length(ds)==0){
        return(NULL)
    }
    else{
        js<-c()
        for(i in 1:length(ds)){
        js<-c(js,list1[ds[i]]$VP$VB,list1[ds[i]]$VP$VBD,list1[ds[i]]$VP$VBG,
        list1[ds[i]]$VP$VBN,list1[ds[i]]$VP$VBP,list1[ds[i]]$VP$VBZ)
        }
    return(js)
    }
}

extract_subject<-function(list1){
    sd<-names(list1)
    ds<-which(sd %in% "NP")
    if(length(ds)==0){
        return(NULL)}
    else{
        js<-c() 
        for(i in 1:length(ds)){
            js<-c(js,list1[ds[i]]$NP$NN,list1[ds[i]]$NP$NNP,list1[ds[i]]$NP$NNPS,
            list1[ds[i]]$NP$NNS)
        }
        return(js)
    }
}

我将这些函数应用于某些嵌套列表。当我将这些函数应用于同一个列表时,extract_verb函数工作正常 - 但extract_subject函数给出如下错误:

Error in list1[ds[i]]$NP$NN : $ operator is invalid for atomic vectors

可能是什么原因?我正在应用函数的嵌套列表s5是:

s5.

$NP
[1] ""

$NP
$NP$JJ
[1] "Invoice"

$NP$NN
[1] "number"


$CC
[1] "and"

[[4]]
[[4]]$NP
[1] NA

[[4]]$NP
[[4]]$NP$DT
[1] "the"

[[4]]$NP$NN
[1] "number"


[[4]][[3]]
[[4]][[3]]$VP
[[4]][[3]]$VP$VBN
[1] "mentioned"


[[4]][[3]][[2]]
[[4]][[3]][[2]]$PP
[[4]][[3]][[2]]$PP$IN
[1] "in"


[[4]][[3]][[2]][[2]]
[[4]][[3]][[2]][[2]]$NP
[1] ""

[[4]][[3]][[2]][[2]]$NP
[[4]][[3]][[2]][[2]]$NP$DT
[1] "the"

[[4]][[3]][[2]][[2]]$NP$NN
[1] "Bill"


[[4]][[3]][[2]][[2]][[3]]
[[4]][[3]][[2]][[2]][[3]]$PP
[[4]][[3]][[2]][[2]][[3]]$PP$IN
[1] "of"


[[4]][[3]][[2]][[2]][[3]][[2]]
[[4]][[3]][[2]][[2]][[3]][[2]]$NP
[[4]][[3]][[2]][[2]][[3]][[2]]$NP$NNP
[1] "Lading"

extract_verb按预期返回NULL

extract_verb(s5)
NULL

但是extract_subject会出错。

extract_subject(s5)
Error in list1[ds[i]]$NP$NN : $ operator is invalid for atomic vectors

s5的输出输出如下。

dput(s5)
structure(list(NP = "", NP = structure(list(JJ = "Invoice", NN = "number"), .Names = c("JJ", 
"NN")), CC = "and", structure(list(NP = NA_real_, NP = structure(list(
    DT = "the", NN = "number"), .Names = c("DT", "NN")), structure(list(
    VP = structure(list(VBN = "mentioned"), .Names = "VBN"), 
    structure(list(PP = structure(list(IN = "in"), .Names = "IN"), 
        structure(list(NP = "", NP = structure(list(DT = "the", 
            NN = "Bill"), .Names = c("DT", "NN")), structure(list(
            PP = structure(list(IN = "of"), .Names = "IN"), structure(list(
                NP = structure(list(NNP = "Lading"), .Names = "NNP")), .Names = "NP")), .Names = c("PP", 
        ""))), .Names = c("NP", "NP", ""))), .Names = c("PP", 
    ""))), .Names = c("VP", ""))), .Names = c("NP", "NP", ""))), .Names = c("NP", 
"NP", "CC", ""))

0 个答案:

没有答案