我有一个 .csv 文件,无法处理,因为数字使用逗号表示小数,这会导致在 R 中读取文件时出现问题。Excel 将逗号解释为小数,而 R 使用点。当我将数据加载到 R 中时,我想用点替换逗号。以下是我尝试过的一些方法:
方法一:
data <- read.csv2("cleaned_data.csv", stringsAsFactors = FALSE)
data$Daily_Loss <- as.numeric(gsub(",", ".", data$Daily_Loss))
data$Total_Loss <- as.numeric(gsub(",", ".", data$Total_Loss))
data$loss_2023 <- as.numeric(gsub(",", ".", data$loss_2023))
data$loss_2024 <- as.numeric(gsub(",", ".", data$loss_2024))
方法2:
data <- read.csv("cleaned_data.csv", sep = ";", dec = ",", stringsAsFactors = FALSE)
data$Daily_Loss <- as.numeric(gsub(",", ".", trimws(data$Daily_Loss)))
data$Total_Loss <- as.numeric(gsub(",", ".", trimws(data$Total_Loss)))
data$loss_2023 <- as.numeric(gsub(",", ".", trimws(data$loss_2023)))
data$loss_2024 <- as.numeric(gsub(",", ".", trimws(data$loss_2024)))
关于如何更有效地解决这个问题有什么建议吗? 之后我想做的是:
total_loss_2023 <- sum(data$loss_2023, na.rm = TRUE)
total_loss_2024 <- sum(data$loss_2024, na.rm = TRUE)
cat("Total Loss in 2023: ", total_loss_2023, "\n")
cat("Total Loss in 2024: ", total_loss_2024, "\n")
欢迎任何帮助! 这是我试图转换为不同格式的表格的一部分。
要有效处理逗号小数,请尝试:
data <- read.csv2("cleaned_data.csv", dec = ",", stringsAsFactors = FALSE)
read.csv2()
专为带有分号分隔符和逗号小数点的欧洲风格 CSV 文件而设计。
如果这不起作用,您可以使用它来替换逗号:
data <- read.csv("cleaned_data.csv", stringsAsFactors = FALSE)
# Convert all numeric columns at once
numeric_cols <- c("Daily_Loss", "Total_Loss", "loss_2023", "loss_2024")
data[numeric_cols] <- lapply(data[numeric_cols], function(x) as.numeric(gsub(",", ".", x)))