r - 一个对象可以接受 R 中相同参数的不同类型吗?
问题描述
是否可以让一个对象接受 R 中相同参数的多种类型?
假设我想创建一个名为taxpayer
with 和 attribute的对象id
。一个纳税人可以由 识别,1234
而另一个纳税人可以由 识别Smith, John
。我怎么能适应这个领域有多种类型的事实id
呢?
我认识到我可以将参数设置为character
字段并1234
作为字符串输入,然后进行转换,但想问一下是否有解决方法。
解决方案
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"
推荐阅读
- javascript - 所有 Discord 标记类型的正则表达式模式
- php - codeigniter 中的动态菜单和角色权限
- flyway - Flywaydb 用于迁移的多个配置文件失败
- vba - 使用 msoFileDialogFolderPicker 获取文件夹路径
- python - 加快numpy解决
- java - Java 8 Streams 查找元素并将其添加到新列表的开头
- android - recyclerview notifyDataSetChanged 停止检测 recyclerview 的分页结束
- java - 在 Android Studio 中连接到数据库的基本 URL
- java - JTableModel 行错误添加
- swift - Xcode 9 中的 Swift 4 - 如何轻量级 Core Data 迁移?