r - 如何使用公开数据将字符串转换为 R 中的数值
问题描述
我是健康科学领域的数据科学初学者。我正在尝试在将其用于分析之前清理我的数据集。
我有 R 的初学者经验,在将字符串转换为数值时需要一些帮助,以便我可以对变量进行分析。
在公开可用的数据中,有一个字符变量,它以李克特量表询问人们对医疗保健系统的看法,但其在数据集中的编码方式是“1 - 糟糕;2;3;4;... 10 - 出色的”
我要做的就是:
1)将“1 - 可怕”转换为“1”,与 10 相同
。2)我还想省略所有“不知道/拒绝”——从我的分母中删除它.
我做了一些初步搜索,发现了一些功能(strsplit),但我很难将它应用到我的情况
解决方案
欢迎来到 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
) 的属性,但它可能合适,也可能不合适。
推荐阅读
- python - 如何仅使用 Behave 获得最终摘要
- angular - Angular:遵循所有步骤,但模式引导程序不起作用
- python - 由于 RAM 使用过多,我的 google colab 会话崩溃
- reactjs - 代码 - 笔问题:为什么我的元胞自动机反应项目不起作用?
- python - 使用 matplotli、pandas 和 python 绘制基于事件的错误
- python - 提取数据框中一个日期的位置
- reactjs - react js axios没有显示来自django rest api的图像
- javascript - 通过将键传递给 react 和 lodash 中的对象数组来获取值
- c# - 将类名传递给 GenericMethod
, 当 className 存储为 String - reactjs - 待办事项列表上的编辑功能