简体   繁体   中英

R - Object not found in user-defined function

So I've seen this question asked multiple times before, but none of the other answers I've tried seem to work. When I run the below function, I get: "Error: object 'x' not found."

xpermntotable <- function(x,y,z){
  xmovematrix <- matrix(unlist(xpermn), ncol = 3, byrow = TRUE)
  for(i in 1:120){
    xmove1 <- xmovematrix[i,1]
    xmove2 <- xmovematrix[i,2]
    xmove3 <- xmovematrix[i,3]
    print(x)
    xtemp <- filter_(fullTable, .dots=list(
      bquote(.(as.name(xmove1)) == x), 
      bquote(.(as.name(xmove2)) == y), 
      bquote(.(as.name(xmove3)) == z)))
    xwin <- rbind(xwin, xtemp)
  }
}

xpermntotable(1,2,3)

The problem seems to be rooted in the specific part of the function below, where the "x" (and presumably the "y" and "z") are not being read properly:

xtemp <- filter_(fullTable, .dots=list(
          bquote(.(as.name(xmove1)) == x), 
          bquote(.(as.name(xmove2)) == y), 
          bquote(.(as.name(xmove3)) == z)))

Solutions I have tried:

  • Containing the "x" variable in as.name(x), or eval(x)

So after more digging into the bquote function, I realised that my solution was there all along. The x, y, and z variables needed to be wrapped with

.() 

The below code works:

xpermntotable <- function(x,y,z){
  xmovematrix <- matrix(unlist(xpermn), ncol = 3, byrow = TRUE)
  for(i in 1:120){
    xmove1 <- xmovematrix[i,1]
    xmove2 <- xmovematrix[i,2]
    xmove3 <- xmovematrix[i,3]
    xtemp <- filter_(fullTable, .dots=list(
      bquote(.(as.name(xmove1)) == .(x)), 
      bquote(.(as.name(xmove2)) == .(y)), 
      bquote(.(as.name(xmove3)) == .(z))))
    xwin <- rbind(xwin, xtemp)
    return(xwin)
  }
}


xwin <- xpermntotable(1,2,3)

More information on the bquote function here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM