Is there an easier way to access attributes of a class in R, can I use dot notation?

后端 未结 4 1984
暖寄归人
暖寄归人 2021-01-30 17:46

I have created an object in R that contains several attributes. How can I easily access them?

I can do:

attr(x, attributeName)

or:

4条回答
  •  忘了有多久
    2021-01-30 18:01

    Example of using the match.length attribute that is returned from regexpr:

    Three strings in a vector, first and third include an embedded string:

    data=c("Chapter 1",
           "no quoted string is embedded in this string",
           "Appendix")
    

    Use regexpr to locate the embedded strings:

    > locations <- regexpr("\"(.*?)\"", data)
    

    Matches are in the first string (at 9 with length 10) and third string (at 11 with length 15):

    > locations
    [1]  9 -1 11
    attr(,"match.length")
    [1] 10 -1 15
    attr(,"useBytes")
    [1] TRUE
    

    Vector from the attribute:

    > attr(locations,"match.length")
    [1] 10 -1 15
    

    Use substr and the attribute vector to extract the strings:

    > quoted_strings=substr( data, 
                             locations, 
                             locations+attr(locations,"match.length")-1 )    
    > quoted_strings
    [1] "\"ch4.html\""      ""                  "\"appendix.html\""
    

    Maybe you'd like to remove the embedded quote characters from your strings:

    > gsub("\"", "", quoted_strings)
    [1] "ch4.html"      ""              "appendix.html"
    

    An alternative is to use regmatches:

    > regmatches(data,locations)
    [1] "\"ch4.html\""      "\"appendix.html\""
    

提交回复
热议问题