英文:
How to resolve Error in .checkTypos(e, names_x) . Error received while using gsub function in R
问题
In my data, column names are written as following:
D/T Temp [degCelc] Pres [hPa] SRad [W/m2] Rain [mm] ARad [W/m2] Moist [%] K [%] Temp1 Press1
I want to change the column names to:
D/T Temp Pres SRad Rain ARad Moist K Temp1 Press1
correct_column_names <- function(dt_list){
lapply(dt_list, FUN = function(x){
colnames(x) <- gsub("[degCelc]", "", colnames(x))
colnames(x) <- gsub("[hPa]", "", colnames(x))
colnames(x) <- gsub("[W/m**2]", "", colnames(x))
colnames(x) <- gsub("[mm]", "", colnames(x))
colnames(x) <- gsub("[%]", "", colnames(x))
return(x)
})
}
This ran successfully.
Later as one step in the code, I selected columns to process by:
sel_col <- c('D/T', 'Temp', 'Pres', 'SRad', 'Rain', 'ARad')
This gives me error:
Error in .checkTypos(e, names_x) :
Object 'Temp1' not found. Perhaps you intended Moist [%], K [%] or 2 more
英文:
In my data, column names are written as following
D/T Temp [degCelc] Pres [hPa] SRad [W/m**2] Rain [mm] ARad [W/m**2] Moist [%] K [%] Temp1 Press1
I want to change the column names to
D/T Temp Pres SRad Rain ARad Moist K Temp1 Press1
correct_column_names <- function(dt_list){
lapply(dt_list, FUN = function(x){
colnames(x) <- gsub("[degCelc]", "", colnames(x))
colnames(x) <- gsub("[hPa]", "", colnames(x))
colnames(x) <- gsub("[W/m**2]", "", colnames(x))
colnames(x) <- gsub("[mm]", "", colnames(x))
colnames(x) <- gsub("[%]", "", colnames(x))
return(x)
})
}
This ran successfully.
Later as one step in the code, I selected columns to process by
sel_col <- c('D/T', 'Temp', 'Pres', 'SRad', 'Rain', 'ARad')
This gives me error:
Error in .checkTypos(e, names_x) :
Object 'Temp1' not found. Perhaps you intended Moist [%], K [%] or 2 more
答案1
得分: 1
这是你想要的:
cols <- c("D/T", "Temp [degCelc]", "Pres [hPa]", "SRad [W/m**2]", "Rain [mm]", "ARad [W/m**2]", "Moist [%]", "K [%]", "Temp1", "Press1")
# 使用基础 R
gsub("\\[.*\\]", "", cols)
# 或者使用 tidyverse
library(tidyverse)
str_replace(cols, "\\[.*\\]", "")
问题在于 gsub("\\[.*\\]", "", colnames(x))
中,方括号没有被转义,所以它们需要被转义 (这是一个关于 R 中正则表达式的良好指南)。这样它将匹配 "h"、"P" 或 "a" 中的任何一个字符,而不是方括号,也不是它们前面的空格:
gsub("\\[degCelc\\]", "", "Temp [degCelc]") # [1] "Tmp []"
英文:
This is what you want:
cols <- c("D/T", "Temp [degCelc]", "Pres [hPa]", "SRad [W/m**2]", "Rain [mm]", "ARad [W/m**2]", "Moist [%]", "K [%]", "Temp1", "Press1")
# using base R
gsub(" \\[.*\\]", "", cols)
# or using tidyverse
library(tidyverse)
str_replace(cols, " \\[.*\\]", "")
The issue is that in gsub("[hPa]", "", colnames(x))
, the square brackets haven't been escaped, so they need to be escaped (this is a good guide to regex in R). So it matches any of "h", "P, or "a"- not the square brackets, nor the space before them:
gsub("[degCelc]", "", "Temp [degCelc]") # [1] "Tmp []"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论