在R语言中处理混合数据CSV:将非整数取整为整数
Hey George, no stress—let's break this down simply so you can get those non-integer values rounded up or down without hassle. Since you've already got the CSV loaded into R, here's what to do next:
Step 1: Check your data structure first
First, let's make sure we know which columns are numeric (the ones we need to adjust) and which are character (we'll leave these alone). Run this command to get a quick overview:
# Replace 'df' with whatever you named your data frame when reading the CSV str(df)
You'll see labels like chr (character) or num (numeric) next to each column name—we only care about the num ones for rounding.
Step 2: Round non-integers (two easy methods)
Method 1: Basic R (no extra packages needed)
If you don't want to install new packages, use a simple loop that automatically skips character columns:
# Loop through each column in your data frame for (col_name in names(df)) { # Only process numeric columns if (is.numeric(df[[col_name]])) { # Use ceiling() to round UP, or floor() to round DOWN df[[col_name]] <- ceiling(df[[col_name]]) # If you want standard rounding (e.g., 2.3 → 2, 2.6 →3), use round() instead: # df[[col_name]] <- round(df[[col_name]]) } }
Method 2: Tidyverse (cleaner, more readable)
If you don't mind installing a popular R package for data manipulation, dplyr makes this super straightforward:
# First install the package if you haven't already (run once) install.packages("dplyr") # Load the package library(dplyr) # Use mutate_if to target only numeric columns and apply your rounding function df <- df %>% mutate_if(is.numeric, ceiling) # Swap ceiling() for floor() or round() as needed
Step 3: Fix edge cases (if some numbers are stored as text)
Sometimes CSV files load numeric values as character strings (e.g., if they had commas or quotes). If you notice a column that should be numeric but shows up as chr, convert it first:
# Example: Convert a column named "available_beds" to numeric then round df$available_beds <- ceiling(as.numeric(df$available_beds))
Or use this dplyr trick to auto-fix all character columns that can be converted to numbers:
df <- df %>% mutate_if( # Check if the column can be safely converted to numeric function(x) all(!is.na(as.numeric(x))), # Convert to numeric then round function(x) ceiling(as.numeric(x)) )
Step 4: Verify your work
Double-check that all numeric values are now integers with these commands:
# Look at the first 6 rows of your data head(df) # Get a summary of numeric columns to confirm no decimals remain summary(df)
That's it—you should have all your non-integer values rounded to integers now, with your character data untouched!
内容的提问来源于stack exchange,提问作者George

