如何用某些整数值替换列的某些字符串类型的值?

时间:2019-05-24 10:30:54

标签: r

在R生存包的 variable "instance_count" { default = 3 } variable "hostnames" { default = ["testcase_1.sh", "testcase_2.sh", "testcase_3.sh"] } data "template_file" "user-data" { count = "${length(var.hostnames)}" template = "${file("${element(var.hostnames, count.index)}")}" } resource "aws_instance" "application" { count = "${var.instance_count}" ami = "${var.ami}" availability_zone = "${var.availability_zone}" ebs_optimized = "${var.ebs_optimized}" instance_type = "${var.instance_type}" key_name = "${var.key_name}" monitoring = "${var.monitoring}" vpc_security_group_ids = ["${var.security_group_ids}"] subnet_id = "${var.subnet_id}" associate_public_ip_address = "${var.associate_public_ip_address}" iam_instance_profile = "${var.iam_instance_profile}" user_data = "${element(data.template_file.user- data.*.rendered, count.index)}" tags = "${merge(var.tags, map("Name", format("%s", var.instance_name)))}" } 数据集中,我目前正在研究veteran列。特别是,我需要按如下所示用一些整数值代替列的当前字符串值。

celltype

但是R抱怨是这样的:

veteran[veteran$celltype == "squamous",]$celltype <- 1
veteran[veteran$celltype == "smallcell",]$celltype <- 2
veteran[veteran$celltype == "adeno",]$celltype <- 3
veteran[veteran$celltype == "large",]$celltype <- 4

我在这里做什么错了?

1 个答案:

答案 0 :(得分:1)

在退伍军人数据集中,列单元格类型实际上是类型因子。 R将因子视为带标签的整数。这在某些机器学习算法中非常有用,因为它们接受数字,但不接受字符串。

在您的情况下,由于您对整数感兴趣,因此可以执行以下操作:

veteran$celltype <- as.numeric(veteran$celltype)

就足够了。

您可以找到有关factors here的更多信息-向下滚动到“因子”部分。