Tried to add a function for R logic. Please test.