首页 > 解决方案 > 如何使用公开数据将字符串转换为 R 中的数值

问题描述

我是健康科学领域的数据科学初学者。我正在尝试在将其用于分析之前清理我的数据集。

我有 R 的初学者经验,在将字符串转换为数值时需要一些帮助,以便我可以对变量进行分析。

在公开可用的数据中,有一个字符变量,它以李克特量表询问人们对医疗保健系统的看法,但其在数据集中的编码方式是“1 - 糟糕;2;3;4;... 10 - 出色的”

我要做的就是:
1)将“1 - 可怕”转换为“1”,与 10 相同
。2)我还想省略所有“不知道/拒绝”——从我的分母中删除它.

我做了一些初步搜索,发现了一些功能(strsplit),但我很难将它应用到我的情况

标签: rstringnumeric

解决方案


欢迎来到 SO!您应该查看此帮助页面,其中包含一些关于如何让您的问题更容易回答的提示。值得注意的是,您应该提供一个适当的示例。这可能令人生畏,但如果你设法找到,str_split那么你显然有能力深入挖掘。我建议您选择R 的非常易于访问的免费介绍之一。

# This is the bare minimum you should provide us with

likert <- c("1 - terrible", "2 - bad", 
            "3 - average", "4 - good", "5 - excellent", "Don't know")


# This seems to be what you're attempting
library(stringr)

likert_numeric <- as.numeric(str_extract(string = likert, pattern = "\\d")) 
# str_extract will take out the first occurrence of the pattern in the string, still as a string
# \\d tells R to look for one digit

likert_numeric
#> [1] 1 2 3 4 5 NA

# But perhaps you just want to code the variable as a factor, 
# which will tell R to treat it appropriately in statistical settings
likert_factor <- as.factor(likert)

likert_factor
#> [1] 1 - terrible  2 - bad       3 - average   4 - good      5 - excellent
#> Levels: 1 - terrible 2 - bad 3 - average 4 - good 5 - excellent

您可能想玩弄数字版本只是为了获得一些快速而肮脏的结果;但从长远来看,你想知道什么是因素以及如何使用它们。

编辑: 至于忽略 NA 值,您需要告诉我们您要做什么。R 中的许多函数具有忽略 NA 值 ( na.rm = TRUE) 的属性,但它可能合适,也可能不合适。


推荐阅读