Reputation: 63
I am trying to convert a data frame in R to a reference class object. Sorry I am an R newbie but I am unable to find the answer to this anywhere!
The class is defined as follows:
LongitudinalData <- setRefClass(
"LongitudinalData",
fields = list(
id = "numeric",
timepoint = "numeric",
value = "numeric",
visit = "numeric",
room = "character"
),
methods = list(
print = function(id) {
######
},
summary = function(x, id) {
sumOut <- x %>%
group_by(id, visit, room) %>%
select(id, visit, room, value) %>%
filter(id == id) %>%
summarise(valMean = mean(value)) %>%
spreadOut <- sumOut %>%
spread(room, valMean)
spreadOut
}
) )
I need a function to convert a data frame (with the same column names as the class fields) to the Longitudinal Data class and call the print and summary methods of the class in order to interrogate it.
I am unclear how I should go about this as I am trying to initialize an instance of the class that has multiple rows. I cannot say that id = 14 or whatever and call the value with x$id. I am also sure that the data still needs to be read as a data frame somewhere in order to use the dplyr pipe operator %>%, so I am confused even further. I have no idea how I should define the fields of the new instance of the class.
Can anyone give me some pointers on how to go about this?
Thanks in advance for any help.
Upvotes: 3
Views: 3352
Reputation: 21
This is working for me:
# Load Data
library(readr)
data <- read_csv("MIE.csv")
# Using Reference Classes
# Creating the constructor for only the class and fields for now. Methods
# will be added later.
LongitudinalData <- setRefClass("longitudinalData",
fields = list(id = "integer",
visit = "integer",
room = "character",
value = "numeric",
timepoint = "integer"),
methods =
list(print.LongtitudinalData=function(){},
subject.LongtitudinalData=function(){}
)
)
# helper function to initialize LongtidudinalData
make_LD = function(df){
LongitudinalData$new(
id = df$id,
visit = df$visit,
room = df$room,
value = df$value,
timepoint = df$timepoint )
}
# Create new object 'x' with class LongtitudinalData and data from 'MIE'data
x <- make_LD(data)
print(class(x))
print(x)
Upvotes: 2