R语言中如何让函数返回两个不同数据类型的列?
问题原因
你遇到的类型转换问题是因为cbind()默认会优先生成矩阵,矩阵要求所有元素的数据类型必须一致,所以当你把字符型的行名和数值型的计算结果合并时,数值会被强制转换为字符型。
修改方案
方案1:直接构造数据框(最常用)
直接用data.frame()生成结果,数据框支持存储不同类型的列,能自动保留原有数据类型:
TypeCombo <- function(type1, type2, type3) { data.frame( row_name = row.names(TypeChart), calc_result = TypeChart[,type1] * TypeChart[,type2] * TypeChart[,type3], stringsAsFactors = FALSE ) }
如果使用R 4.0及以上版本,stringsAsFactors默认值已经是FALSE,这个参数可以省略。
方案2:返回列表格式
如果需要返回列表类型的结果,直接把两部分内容放到列表结构中即可:
TypeCombo <- function(type1, type2, type3) { list( row_name = row.names(TypeChart), calc_result = TypeChart[,type1] * TypeChart[,type2] * TypeChart[,type3] ) }
方案3:使用cbind的data.frame模式
如果习惯用cbind的语法,可以用cbind.data.frame()替代默认的cbind,它会直接生成数据框而非矩阵,不会强制统一所有元素的类型:
TypeCombo <- function(type1, type2, type3) { cbind.data.frame( row_name = row.names(TypeChart), calc_result = TypeChart[,type1] * TypeChart[,type2] * TypeChart[,type3], stringsAsFactors = FALSE ) }
内容的提问来源于stack exchange,提问作者moistnar
相关产品推荐
相关产品推荐

