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

如何将Stata中生成变量的cond条件代码转换为R代码?

Got it, let's break this down and convert that Stata code to R.

First, let's recap what your Stata code does: it creates a new variable a01sb that takes the value of a01 only if b01 is not equal to 1 AND c01 is not equal to 1. If either of those conditions fails, a01sb gets set to 0.

In R, there are a couple of common ways to replicate this logic, depending on whether you prefer base R or tidyverse tools. Here are both approaches:

1. Base R with ifelse()

The base R ifelse() function works exactly like Stata's cond()—it takes a condition, a value for when the condition is TRUE, and a value for when it's FALSE:

# Replace `df` with the name of your actual data frame
df$a01sb <- ifelse(df$b01 != 1 & df$c01 != 1, df$a01, 0)

2. Tidyverse (dplyr) Approach

If you use the tidyverse for data manipulation, you can use mutate() paired with either ifelse() or the more readable case_when() (great if you might add more conditions later):

library(dplyr)

# Using ifelse inside mutate
df <- df %>%
  mutate(a01sb = ifelse(b01 != 1 & c01 != 1, a01, 0))

# Using case_when for clearer condition handling
df <- df %>%
  mutate(a01sb = case_when(
    b01 != 1 & c01 != 1 ~ a01,
    TRUE ~ 0  # Catch-all for all other scenarios
  ))

A quick check: Make sure b01, c01, and a01 are all columns in your data frame. If you're working with standalone vectors instead of a data frame, just drop the df$ prefix in the base R version, or adjust the tidyverse code accordingly.

内容的提问来源于stack exchange,提问作者Timitrov

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:04:16