将多个列中的温度数据从开尔文转换为摄氏度。

huangapple go评论52阅读模式
英文:

Convert temperature data from Kelvin to Celsius in multiple columns

问题

我有一个包含多列以开尔文表示的温度数据的数据集。我想将其转换为摄氏度。

Sr. StationID   MaxTemp   MinTemp  MeanTemp  Prec   
1   5320         280       270       275      1.2

我正在使用以下代码来将其中一列(MaxTemp)转换为摄氏度。我想添加更多列的名称。

DF %>%
  mutate(across(.cols = starts_with("MaxTemp"), .fns = function(x) x - 273.15))
英文:

I have a dataset with multiple columns of temperature data in Kelvin. I want to convert it to celsius.

Sr. StationID   MaxTemp   MinTemp  MeanTemp  Prec   
1   5320         280       270       275      1.2

I am using this code which helps to convert only one column (MxTemp). I want to add more column names.

DF %>%
  mutate(across(.cols = starts_with("MaxTemp"),.fns = function(x) x - 273.15))

答案1

得分: 0

你可以使用 ends_with,而不是 starts_with

DF %>% mutate(across(.cols = ends_with("Temp"),.fns = function(x) x - 273.15))
英文:

instead of starts_with, you could use ends_with:

DF %>% mutate(across(.cols = ends_with("Temp"),.fns = function(x) x - 273.15))

答案2

得分: 0

使用data.table的解决方案

library(data.table)
setDT(DF) # 将其转换为data.table

tcols = grep("Temp", names(DF))
DF[, (tcols) := .SD - 273.15, .SDcols = tcols] # 列通过引用更新

如果您有任何其他问题,可以随时提出。

英文:

solution using data.table

library(data.table)
setDT(DF) # make it a data.table

tcols = grep("Temp", names(DF))
DF[, (tcols) := .SD - 273.15, .SDcols = tcols] # columns updated by reference

huangapple
  • 本文由 发表于 2023年2月24日 16:07:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/75554001.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定