基于列字符与另一列条件新增列的R语言数据处理需求
Solution for Conditional Column Assignment in R
Hey there! Let's tackle this problem where we need to dynamically set the agent and partner columns based on the value in the Subject column. The core idea is to swap the substring positions when Subject is "B1" or "B2", compared to when it's "A1" or "A2".
Method 1: Base R with ifelse()
This approach uses base R's built-in ifelse() function to apply conditional logic row-by-row:
# Assign agent column df$agent <- ifelse( df$Subject %in% c("A1", "A2"), substr(df$Filename, start = 16, stop = 25), substr(df$Filename, start = 27, stop = 36) ) # Assign partner column (reverse logic of agent) df$partner <- ifelse( df$Subject %in% c("A1", "A2"), substr(df$Filename, start = 27, stop = 36), substr(df$Filename, start = 16, stop = 25) )
How it works:
- For rows where
Subjectis "A1" or "A2":agentpulls characters 16-25 fromFilenamepartnerpulls characters 27-36 fromFilename
- For rows where
Subjectis "B1" or "B2" (or any value not in "A1"/"A2"):agentuses the 27-36 range (originally partner's position)partneruses the 16-25 range (originally agent's position)
Method 2: Tidyverse with dplyr::case_when()
If you prefer a more readable, explicit approach (especially for more complex conditions), use case_when() from the dplyr package:
library(dplyr) df <- df %>% mutate( agent = case_when( Subject %in% c("A1", "A2") ~ substr(Filename, 16, 25), Subject %in% c("B1", "B2") ~ substr(Filename, 27, 36), TRUE ~ NA_character_ # Optional: Handle unexpected Subject values ), partner = case_when( Subject %in% c("A1", "A2") ~ substr(Filename, 27, 36), Subject %in% c("B1", "B2") ~ substr(Filename, 16, 25), TRUE ~ NA_character_ ) )
How it works:
case_when()lets you list out specific conditions and their corresponding actions, making the logic easy to follow.- The
TRUE ~ NA_character_line is optional but useful: it assignsNAto any rows whereSubjectisn't "A1"/"A2"/"B1"/"B2", so you can spot unexpected values quickly.
Testing with your sample data
Using your example dataset, here's the expected output:
| Filename | Subject | agent | partner |
|---|---|---|---|
| 161014_1_A1_B1_1880129006_1801004016_1 | A1 | 1880129006 | 1801004016 |
| 161214_1_A1_B1_1861317003_1801206008_1 | B1 | 1801206008 | 1861317003 |
| 170202_1_A2_B1_1860415029_1750730086_2 | A2 | 1860415029 | 1750730086 |
You can see the logic works as expected: the B1 row swaps the agent/partner values compared to the A1/A2 rows.
内容的提问来源于stack exchange,提问作者RenaSo
相关产品推荐
相关产品推荐

