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

求助:使用高级条件/循环函数在R(tidyverse)中创建新列

Creating New Columns in Tidyverse (R)

Hey there! Since you're focusing on the tidyverse and working with this dataset, let's walk through how to create new columns using tidyverse tools—these are usually cleaner and more efficient than manual loops for most data manipulation tasks.

First, let's confirm your dataset structure (I'll fill in the partial row for D to make it complete for examples):

library("tibble")
myData <- frame_data(
  ~id, ~r1, ~r2, ~r3, ~r4, ~r5, ~r6, ~r7, ~r8, ~r9, ~r10, ~r11, ~r12, ~r13, ~r14, ~r15, ~r16,
  "A", 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  "B", 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  "C", 2, 2, 2, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 2, 2, 2,
  "D", 1, 1, 2, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2
)

Common Scenarios & Solutions

Since you mentioned "advanced if/then/loop functions", here are a few typical use cases using tidyverse's dplyr and purrr packages (core parts of the tidyverse):

1. Count the number of 1s across r1-r16

If you want to create a column that counts how many times 1 appears in each row's r columns:

library(dplyr)

myData <- myData %>%
  mutate(count_ones = rowSums(select(., starts_with("r")) == 1))

This avoids loops entirely by using vectorized operations—way faster for large datasets.

2. Categorize rows based on conditions (if/then logic)

Suppose you want to create a category column:

  • "All Twos" if every r value is 2
  • "Mostly Ones" if 10+ r values are 1
  • "Mixed" otherwise

Use case_when (tidyverse's flexible if/then tool):

myData <- myData %>%
  mutate(row_category = case_when(
    rowSums(select(., starts_with("r")) == 2) == 16 ~ "All Twos",
    rowSums(select(., starts_with("r")) == 1) >= 10 ~ "Mostly Ones",
    TRUE ~ "Mixed"
  ))

3. Apply a custom function across rows (loop-like logic with purrr)

If you need a more custom operation (like checking sequences of 1s/2s), use purrr::pmap to iterate over rows:

library(purrr)

# Example: Check if the row starts with three 2s
starts_with_three_twos <- function(r1, r2, r3, ...) {
  r1 == 2 && r2 == 2 && r3 == 2
}

myData <- myData %>%
  mutate(starts_with_3twos = pmap_lgl(select(., starts_with("r")), starts_with_three_twos))

Key Notes

  • Tidyverse encourages avoiding explicit for loops when possible—vectorized functions (like rowSums) or purrr's iteration tools are more readable and performant.
  • If you have a specific condition in mind for your new column, feel free to share more details, and we can refine this further!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:23:23