xfrostyy
xfrostyy

Reputation: 47

Can an object accept different types for the same parameter in R?

Is it possible to have an object accept multiple types for the same parameter in R?

Say I want to create an object called taxpayer with and attribute id. One taxpayer may be identified by 1234 and the other by Smith, John. How could I accommodate for the fact that there are multiple types that could go in the id field?

I recognize that I could just make the parameter a character field and put in 1234 as a string and convert thereafter, but wanted to ask in case there was a work-around.

Upvotes: 1

Views: 45

Answers (2)

David J. Bosak
David J. Bosak

Reputation: 1624

The above answer was for an S3 style class. For an S4 style class, you can use the "ANY" type specifier, which will take any data type. Here is the same example as above modified for S4:

# Define taxpayer class
taxpayer <- setClass("taxpayer", slots = c(id = "ANY")) 

# Instantiate taxpayer with character ID
t1 <- taxpayer(id = "Smith, John") 
t1
# An object of class "taxpayer"
# Slot "id":
#   [1] "Smith, John"

# Check class
class(t1@id)
# [1] "character"

# Instantiate taxpayer with numeric ID
t2 <- taxpayer(id = 1234)  
t2
# An object of class "taxpayer"
# Slot "id":
#   [1] 1234

# Check class
class(t2@id)
# [1] "numeric"


Upvotes: 0

David J. Bosak
David J. Bosak

Reputation: 1624

R has dynamic typing. The thing you are asking about is the default behavior. If you send in a number, it will treat it as a number. If you send in a character, it will treat it as a string.

Here is an example:


# Define taxpayer class
taxpayer <- function(id) {
  
  # Create new structure of class "taxpayer"
  t <- structure(list(), class = c("taxpayer", "list"))
  
  # Assign ID attribute
  t$id <- id
  
          
  return(t)
}

# Instantiate taxpayer with character ID
t1 <- taxpayer("Smith, John") 
t1
# $id
# [1] "Smith, John"
# 
# attr(,"class")
# [1] "taxpayer" "list"

# Check class
class(t1$id)
# [1] "character"

# Instantiate taxpayer with numeric ID
t2 <- taxpayer(1234)  
t2
# $id
# [1] 1234
# 
# attr(,"class")
# [1] "taxpayer" "list" 

# Check class
class(t2$id)
# [1] "numeric"

Upvotes: 2

Related Questions