R语言入门:如何将数据列中yes/no转换为1、2数值
Hey there! Let's work through this together. You've already made a solid start loading your data, and now we just need to turn those "yes"/"no" values in the glucose column into numerical 1s and 2s (yes=1, no=2). Here are three beginner-friendly methods to get this done:
Method 1: Use ifelse() (most straightforward for new R users)
This function checks each value in the column and replaces it based on your condition—super easy to follow:
# First, confirm your data is loaded and column names are set correctly cell <- read.table(file="tetrahymena.txt", header=TRUE, sep="\t", dec = ".") colnames(cell) <- c("glucose","conc","diameter") # Convert glucose values directly cell$glucose <- ifelse(cell$glucose == "yes", 1, 2)
The logic here is simple: if the value is "yes", swap it for 1; every other value (which should be "no" in your dataset) gets swapped for 2.
Method 2: Convert via factors
Since "yes"/"no" are categorical values, turning them into a factor first then converting to numbers works well—just make sure you set the level order to get the right numbers:
# Load and rename your data as before cell <- read.table(file="tetrahymena.txt", header=TRUE, sep="\t", dec = ".") colnames(cell) <- c("glucose","conc","diameter") # Create a factor with "yes" as the first level (so it becomes 1) cell$glucose <- factor(cell$glucose, levels = c("yes", "no")) # Convert the factor to numeric values cell$glucose <- as.numeric(cell$glucose)
Pro tip: Always specify the levels parameter! If you skip it, R might sort values alphabetically (meaning "no" would become 1, which isn't what you want).
Method 3: Use dplyr (for tidyverse-focused workflows)
If you plan to do more data cleaning later, the dplyr package makes this step clean and readable:
# Install dplyr first if you haven't: install.packages("dplyr") library(dplyr) # Load, rename, and convert in one streamlined pipeline cell <- read.table(file="tetrahymena.txt", header=TRUE, sep="\t", dec = ".") %>% rename(glucose = 1, conc = 2, diameter = 3) %>% # Alternative to colnames() mutate(glucose = case_when( glucose == "yes" ~ 1, glucose == "no" ~ 2 ))
case_when() lets you write out each condition explicitly, which is great if you ever need to handle more than two categories down the line.
Quick check to confirm it worked
After running any of these methods, use summary(cell) or table(cell$glucose) to double-check that your glucose column now has 1s and 2s instead of "yes"/"no".
内容的提问来源于stack exchange,提问作者V.Heik

