` in R, "error : attempt to apply non-function"

2.1k views Asked by At

Below I have shared a code where I am facing an error after trying to Add a child node in a tree I created using the data.tree package of R software. The error says "attempt to apply non-function", I don't know if something is wrong with the type of data I provided or it has to something with the syntax.

> g <- Node$new("T")
> s <- g$AddChild("S")
> n <- g$AddChild("N")
> t <- n$AddChild("T")
> e <- n$AddChild("E")
> u <- e$AddChild("U")
> d <- e$AddChild("D")
> print(g)
      levelName
1 T            
2  ¦--S        
3  °--N        
4      ¦--T    
5      °--E    
6          ¦--U
7          °--D
> g$s$AddChild("F")
Error: attempt to apply non-function
1

There are 1 answers

2
Allan Cameron On BEST ANSWER

Your error comes from the fact that g doesn't have a member called s. It has a member called children, which itself has a member called S (note the capital because you used a capital "S" for the name of the node).

You can access this node in one of two ways: either just with s, since that's the variable in the global environment that you stored as a reference to this node, or by using g$children$S, which is also a direct reference to the same node.

If you really need the references to all these nodes separately in the global environment you could do it the way you have in your example, in which case your last line would just be:

s$AddChild("F")

print(g)
#>       levelName
#> 1 T            
#> 2  ¦--S        
#> 3  ¦   °--F    
#> 4  °--N        
#> 5      ¦--T    
#> 6      °--E    
#> 7          ¦--U
#> 8          °--D

but you may wish to work explicitly from g to avoid having all these extra variables to keep track of, as in the following full reprex:

library(data.tree)

g <- Node$new("T")
g$AddChild("S")
g$AddChild("N")
g$children$N$AddChild("T")
g$children$N$AddChild("E")
g$children$N$children$E$AddChild("U")
g$children$N$children$E$AddChild("D")

print(g)
#>       levelName
#> 1 T            
#> 2  ¦--S        
#> 3  °--N        
#> 4      ¦--T    
#> 5      °--E    
#> 6          ¦--U
#> 7          °--D

g$children$S$AddChild("F")

print(g)
#>       levelName
#> 1 T            
#> 2  ¦--S        
#> 3  ¦   °--F    
#> 4  °--N        
#> 5      ¦--T    
#> 6      °--E    
#> 7          ¦--U
#> 8          °--D

Created on 2020-12-05 by the reprex package (v0.3.0)