You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言:字符型带分隔符小数转数值及散点图添加回归线问题

Fixing Numeric Conversion & Scatter Plot with Regression Line in R

Hey there! I see exactly what's going on here—your data uses non-standard numeric formatting (dots for thousands separators, commas for decimal points) which is why converting straight to numeric gives you NAs. Let's walk through fixing this step by step.

Step 1: Understand the Data Format Issue

Looking at your sample data:

head(alle,6)
      demo       tot besch    usd
1 498.300.775 4.846.423 69,8 1,3705
2 500.297.033 4.891.934 70,3 1,4708
  • Variables like demo and tot use dots as thousands separators
  • besch and usd use commas as decimal points
    R can't parse these automatically as numeric values, so we need to clean them first.

Step 2: Create a Helper Function for Cleaning

Let's make a reusable function that handles both formatting issues:

clean_numeric <- function(x) {
  # First, convert factor to character if needed
  x <- as.character(x)
  # Replace dots (thousands separators) with empty string
  x <- gsub("\\.", "", x)
  # Replace commas (decimal points) with dots
  x <- gsub(",", ".", x)
  # Convert to numeric
  as.numeric(x)
}

Step 3: Apply the Function to All Variables

Now we'll use this function to convert all four variables to numeric:

# Convert each variable
alle$demo <- clean_numeric(alle$demo)
alle$tot <- clean_numeric(alle$tot)
alle$besch <- clean_numeric(alle$besch)
alle$usd <- clean_numeric(alle$usd)

# Verify the conversion worked
str(alle)

You should now see all variables listed as num (numeric) instead of chr or factor.

Step 4: Fit the Regression & Plot

Now that your data is properly formatted, you can fit the linear model without warnings:

# Fit the regression model
reg1 <- lm(tot ~ demo, data = alle)

# Create the scatter plot with regression line
plot(tot ~ demo, data = alle, main = "Scatter Plot of tot vs demo with Regression Line",
     xlab = "demo", ylab = "tot", pch = 16, col = "steelblue")
abline(reg1, col = "darkred", lwd = 2)

This will give you a clean scatter plot with a red regression line overlaid.

Quick Notes

  • If you get any remaining NAs after conversion, double-check your raw data—there might be non-numeric values hiding in some rows (like text or empty cells).
  • The clean_numeric function works for both character and factor inputs, so it's flexible for your data structure.

内容的提问来源于stack exchange,提问作者melooo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:18:31