我很抱歉,因为肯定有很多类似的问题和答案,但我已经try 了一堆建议的答案,遗憾的是没有.

我在一个数据帧(Tempdata)的三列中获得了温度数据.为简单起见,我只是try 一次更改其中一个位置(wentworth.Castle).

这就是我的数据.所有带有".Castle"的柱子都是该站点的温度.缺少值,但这是意料之中的.希望把它们变成NA.

glimpse(tempdata)
Rows: 3,395
Columns: 5
$ Description      <chr> "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", …
$ date.time        <chr> "22/11/2023 09:48", "22/11/2023 10:18", "22/11/2023 10:48", "22/11/2023 11:…
$ site.castle      <chr> "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",…
$ dover.castle     <chr> "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",…
$ wentworth.castle <chr> "9.484 \xb0C", "9.642 \xb0C", "9.768 \xb0C", "9.994 \xb0C", "10.066 \xb0C",…

我已经try 了下面的几种方法,得到了以下错误.

tempdata$wentworth.castle <- gsub(" �C", "", as.numeric(tempdata$wentworth.castle))
#Error in is.factor(x) : invalid multibyte string at '<b0>C'

tempdata$wentworth.castle <- gsub(" \xb0C", "", as.numeric(tempdata$wentworth.castle))
#Error in is.factor(x) : invalid multibyte string at '<b0>C'

tempdata$wentworth.castle = tempdata$wentworth.castle.replace('\u00b0','', regex=True)
#Error: attempt to apply non-function

tempdata$wentworth.castle <- as.numeric(tempdata$wentworth.castle)
#Error: invalid multibyte string at '<b0>C'

我还try 了一种不太健壮的方法,并try 创建一个函数来删除特定数量的字符后的内容,但是这很困难,因为有时我的数据有5个符号数字,有时有6个,所以即使它起作用了,我也会从一些条目中删除一些随机空格.

left = function(string, chat){substr(string, 1, char)}
tempdata$wentworth.castle <- left(tempdata$wentworth.castle, 6)
#Error in as.integer(stop) : 
#  cannot coerce type 'closure' to vector of type 'integer'

推荐答案

这是一个编码问题,无法正确解释度数符号,您可以使用iconv转换,然后使用gsub删除°C:

# data 
wentworth <- c("9.484 \xb0C", "9.642 \xb0C", "9.768 \xb0C", "9.994 \xb0C", "10.066 \xb0C")

gsub(" °C","", iconv(wentworth, from = "ISO-8859-1", to = "UTF-8"))

# [1] "9.484"  "9.642"  "9.768"  "9.994"  "10.066"

# or if you want it numeric, just wrap it
as.numeric(gsub(" °C","", iconv(wentworth, from = "ISO-8859-1", to = "UTF-8")))

# [1]  9.484  9.642  9.768  9.994 10.066

R相关问答推荐

创建重复删除的唯一数据集组合列表

混淆矩阵,其中每列和等于1

根据shiny 应用程序中的数字输入更改图标 colored颜色

在R中列表的结尾添加数字载体

如何使用R中的dhrr函数将李克特量表的因子列从长转换为宽?

如何计算R数据集中每个女性的子元素数量?

如何将R中数据帧中的任何Nas替换为最后4个值

绘制采样开始和采样结束之间的事件

更新R中的数据表(使用data.table)

在R中,我如何使用滑动窗口计算位置,然后进行过滤?

如何使用同比折线图中的个别日

通过初始的shiny 应用更新部署的shiny 应用的数据和参数,其中部署的应用程序显示为URL

使用列中的值来调用函数调用中应使用的其他列

数值型数据与字符混合时如何进行绑定

根据r中每行中的日期序列,使用列名序列创建新列

计算来自单独分组的分幅的值的百分位数

使用&Fill&Quot;在gglot中创建 colored颜色 渐变

在REST API中使用参数R

重写时间间隔模糊连接以减少内存消耗

为什么R列名称忽略具有指定名称的向量,而只关注索引?