1

R を使用して大きな JS オブジェクトを操作しています (ライブラリ rjsonio を使用)。そのため、ネストされたリストがたくさんあり、操作がやや面倒になっています。以下に簡単な例を示します。何らかの形式の「ゲッター」および「セッター」関数を作成して、このオブジェクトを操作しようとしています。周りを見回した後、オブジェクトを再帰して最初に一致したラベルを返す、非常に優れた「ゲッター」関数を見つけました。これは、関数を連鎖させるのに役立つため、特に優れています。ただし、「セッター」関数で同じ効果を得る方法がわかりません。同様の方法で連鎖できる「セッター」関数を作成する方法について何か考えはありますか?

#example, simplified, object
app = list(
  1,
  2,
  d=list(a=123,
         b=456,
         list(
           FirstKey=list(attr1='good stuff', attr2=12345),
           SecondKey=list(attr1='also good stuff', attr2=4321)
           )
         )
  )


#Return a function that returns the value 
#associated with first label that matches 'name'
getByName <- function(name){
  rmatch <- function(x) {
    pos <- match(name, names(x))
    if (!is.na(pos))
      return(x[[pos]])
    for (el in x) {
      if (class(el) == "list") {
        out <- Recall(el)
        if (!is.null(out)) return(out)
      }
    }
  }
  rmatch
}

getFirstKey <- getByName("FirstKey")
getAttr1 <- getByName("attr1")
getAttr2 <- getByName("attr2")

#I like that I can chain these functions together
getAttr1(getFirstKey(app))
getAttr2(getFirstKey(app))

# I would like to be able to do something like this
# But this won't work
###    getAttr1(getFirstKey(app)) <- 9876

# This does work,,, but I loose the ability to chain functions together
# Closure around a replacement function
setterKeyAttr <- function(keyName, attr){
  function(x, value){
    x$d[[3]][[keyName]][[attr]] <- value
    x
  }
}

`setFirstKeyAttr2<-` <- setterKeyAttr("FirstKey", "attr2")
setFirstKeyAttr2(app) <- 22222
#check the answer is correct
getAttr2(getFirstKey(app))

参照: 入力と出力の両方を変更する R デコレーター

http://r.789695.n4.nabble.com/How-to-get-a-specific-named-element-in-a-nested-list-td3037430.html

http://adv-r.had.co.nz/Functions.html

4

1 に答える 1