我从数据记录器下载了一份温度数据表,其中小数点消失了。这是一个片段:
temperature<-c( 227725, 208957, 210834, 214588, 218342)
date<-c("2022-06-14 12:02:01 UTC", "2022-06-14 12:32:01 UTC", "2022-06-14 13:02:01 UTC", "2022-06-14 13:32:01 UTC", "2022-06-14 14:02:01 UTC")
df<-data.frame(date,temperature)
df
date temperature
1 2022-06-14 12:02:01 UTC 227725
2 2022-06-14 12:32:01 UTC 208957
3 2022-06-14 13:02:01 UTC 210834
4 2022-06-14 13:32:01 UTC 214588
5 2022-06-14 14:02:01 UTC 218342
我已经知道小数点应该在前两位数字之后。
有没有办法插入小数点分隔符?
提前致谢!
如果数字可能不全是六位数字,但您确定小数点必须位于第二位数字之后,则以下内容应该有效:
as.character(df$temperature
gsub
将前 2 位数字替换为自身加点 gsub("^(\\d{2})", "\\1.", as.character(df$temperature))
as.numeric(gsub("^(\\d{2})", "\\1.", as.character(df$temperature)))
那么,
df$temperature <- as.numeric(gsub("^(\\d{2})", "\\1.", as.character(df$temperature)))
print(df)
date temperature
1 2022-06-14 12:02:01 UTC 22.7725
2 2022-06-14 12:32:01 UTC 20.8957
3 2022-06-14 13:02:01 UTC 21.0834
4 2022-06-14 13:32:01 UTC 21.4588
5 2022-06-14 14:02:01 UTC 21.8342
另一个基础 R 解决方案:
transform(df, temperature = temperature * 10 ^(2 - nchar(temperature)))
date temperature
1 2022-06-14 12:02:01 UTC 22.7725
2 2022-06-14 12:32:01 UTC 20.8957
3 2022-06-14 13:02:01 UTC 21.0834
4 2022-06-14 13:32:01 UTC 21.4588
5 2022-06-14 14:02:01 UTC 21.8342