为行的子集创建两个变量中的新变量

发布于 2025-02-08 06:02:31 字数 1143 浏览 5 评论 0原文

我需要从两个旧变量的 value>中创建一个新变量(var_new)(var_old_1; var_old_2),但在这两种情况下,仅对于行的一个子集

让我解释一下:

  1. 我有一个索引变量,指示患者代码;称为“患者代码”(H01,H02,H03 ...)

  2. 我需要创建一个新变量。 “ var_new”

  3. 必须从var_old_1或var_old_2分配新变量“ var_new”的值。

因此

(H01,H02,H04)var_new == var_old_1 对于(H03,H05)var_new == var_old_2

dertaborcodevar_old_1var_old_2var_new
H011.11.12.1 1.1
H021.2 1.22.21.2 1.2
H031.31.3 2.32.3 2.3
H041.4 1.42.4 2.4 1.41.4
H051.5 1.5 2.52.5 2.52.5

这只是一个示例。在我的数据集中,我要处理300行,我需要在此方案之后创建32个新变量。因此,一个好的代码将有所帮助。

I need to create a new variable (Var_new) out of the values of two old variables (Var_Old_1; Var_Old_2) but in both cases only for a subset of rows.

Let me explain:

  1. I have an index variable, indicating the patient code; called "patientcode" (H01, H02, H03 ...)

  2. I need to create a new variable. "Var_new"

  3. the values of the new Variable "Var_new" must be assigned from Var_Old_1 or Var_Old_2 depending on the index variable.

So e.g.

for (H01, H02, H04) Var_new == Var_Old_1
for (H03, H05) Var_new == Var_Old_2

patientcodeVar_Old_1Var_Old_2Var_new
H011.12.11.1
H021.22.21.2
H031.32.32.3
H041.42.41.4
H051.52.52.5

This is only an example. In my dataset I'am dealing with 300 rows and I need to create 32 new variables following this scheme. so a good code would be helpful.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

东走西顾 2025-02-15 06:02:31

也许有以下内容?

patientcode_old1 <- c("H01", "H02", "H04")
patientcode_old2 <- c("H03", "H05")

result <- df %>%
  mutate(Var_new = case_when(
          patientcode %in% patientcode_old1 ~ Var_Old_1,
          patientcode %in% patientcode_old2 ~ Var_Old_2,
          TRUE ~ NA_real_
          )
        )

然而,如果您需要以这种方式创建32个新变量,您的描述听起来好像您需要进行大量手动预订?也许想想是否需要创建这些VAR的方式背后有任何规律性。否则,我看不到如何避免进一步的手动努力。

Maybe something like the following?

patientcode_old1 <- c("H01", "H02", "H04")
patientcode_old2 <- c("H03", "H05")

result <- df %>%
  mutate(Var_new = case_when(
          patientcode %in% patientcode_old1 ~ Var_Old_1,
          patientcode %in% patientcode_old2 ~ Var_Old_2,
          TRUE ~ NA_real_
          )
        )

Yet your description sounds like you need to do lots of manual prework if you need to create 32 new variables that way?! Maybe think about if there's any kind of regularity behind the way those vars need to be created. Otherwise I don't see a possibility how to avoid further manual efforts.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文