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

基于列字符与另一列条件新增列的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 Subject is "A1" or "A2":
    • agent pulls characters 16-25 from Filename
    • partner pulls characters 27-36 from Filename
  • For rows where Subject is "B1" or "B2" (or any value not in "A1"/"A2"):
    • agent uses the 27-36 range (originally partner's position)
    • partner uses 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 assigns NA to any rows where Subject isn'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:

FilenameSubjectagentpartner
161014_1_A1_B1_1880129006_1801004016_1A118801290061801004016
161214_1_A1_B1_1861317003_1801206008_1B118012060081861317003
170202_1_A2_B1_1860415029_1750730086_2A218604150291750730086

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:52:08