I am trying to create a new class in R for the first time and I have a hard time.
Question
Can you please show me how one could create a class that inherits from the class "data.frame" but can only contain 3 columns named col1, col2 and col3. All columns must be "numeric" and the relation col1 + col2 = col3 must hold true.
The user could do
ClassName(col1 = rep(10,10), col2 = 1:10)
or
ClassName(col1 = rep(10,10), col3 = 11:20)
or
ClassName(col2 = 1:10, col3 = 11:20)
to create an object of this class. All of the above lines would all yield to a similar output to
data.frame(col1 = rep(10,10), col2 = 1:10, col3 = rep(10,10)+(1:10))
col1 col2 col3
1 10 1 11
2 10 2 12
3 10 3 13
4 10 4 14
5 10 5 15
6 10 6 16
7 10 7 17
8 10 8 18
9 10 9 19
10 10 10 20
What I tried
Here is all I manage to do so far.
setClass("newClass", representation(col1="numeric",col2="numeric",col3="numeric"), contains="numeric")
calc.newClass = function(obj)
{
if (length(obj@col1)==0)
{
return(new("newClass", col1=obj@col3-obj@col2, col2=obj@col2, col3=obj@col3) )
}
if (length(obj@col2)==0)
{
return(new("newClass", col1=obj@col1, col2=obj@col3-obj@col1, col3=obj@col3) )
}
if (length(obj@col3)==0)
{
return(new("newClass", col1=obj@col1, col2=obj@col2, col3=obj@col1+obj@col2) )
}
}
o = calc.newClass(new("newClass", col1=rep(10,10), col3=11:20))
I failed to
- inherit from "data.frame"
- to force the function "calc" to apply automatically at the moment of the construction of an object of the new class.