首页 > 解决方案 > 一个对象可以接受 R 中相同参数的不同类型吗?

问题描述

是否可以让一个对象接受 R 中相同参数的多种类型?

假设我想创建一个名为taxpayerwith 和 attribute的对象id。一个纳税人可以由 识别,1234而另一个纳税人可以由 识别Smith, John。我怎么能适应这个领域有多种类型的事实id呢?

我认识到我可以将参数设置为character字段并1234作为字符串输入,然后进行转换,但想问一下是否有解决方法。

标签: r

解决方案


R 具有动态类型。您要问的是默认行为。如果您发送一个号码,它会将其视为一个号码。如果您发送一个字符,它会将其视为一个字符串。

这是一个例子:


# 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"

推荐阅读