基于百分比创建二元变量:ifelse函数条件设置技术问询
ifelse()创建二元变量marginal Hey Caroline, glad to help with this! The ifelse() function is actually perfect for exactly what you need—no need for more complicated methods. Let's break it down with examples tailored to your UK election data.
基础用法(假设majority是数值型百分比)
First, make sure your majority column is stored as a numeric value (e.g., 7.5 for 7.5%, not a string like "7.5%"). If it's already numeric, you can create the marginal variable in one line:
# Replace 'election_data' with your actual data frame name election_data$marginal <- ifelse(election_data$majority <= 10, 1, 0)
Let's unpack this:
- The first argument in
ifelse()is your condition:election_data$majority <= 10(checks if the majority is 10% or less) - The second argument is what to assign when the condition is true:
1 - The third argument is what to assign when the condition is false:
0
处理带%符号的字符串列
If your majority column includes the percent symbol (e.g., "8.2%"), you'll need to convert it to a numeric value first. Here's how to do that in one go:
# Convert percentage string to numeric, then create marginal election_data$marginal <- ifelse( as.numeric(sub("%", "", election_data$majority)) <= 10, 1, 0 )
The sub("%", "", ...) removes the % symbol, and as.numeric() turns the remaining text into a number.
可选:用dplyr(tidyverse)更简洁的写法
If you're using the tidyverse ecosystem, you can use mutate() with either ifelse() or case_when() for cleaner code:
library(dplyr) # Using ifelse() with dplyr election_data <- election_data %>% mutate(marginal = ifelse(majority <= 10, 1, 0)) # Or using case_when() (great for multiple conditions later) election_data <- election_data %>% mutate(marginal = case_when( majority <= 10 ~ 1, TRUE ~ 0 ))
All these methods will give you exactly the binary marginal variable you need for your 2015 UK election turnout analysis.
内容的提问来源于stack exchange,提问作者Caroline Herlin

