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

如何在R数据框指定列中替换重复值为NA及生成隔行NA

Solution for Two Dataframe Column Tasks in R

Let's work through your two requirements using the sample dataframe you provided. First, here's a complete version of the dataframe we'll use (I added dummy values to the incomplete 0 column for demonstration):

df <- structure(
  list(
    condition = c(4, 4, 6, 6, 8, 8),
    main = structure(
      c(2L, 1L, 1L, 2L, 1L, 2L),
      .Label = c("0", "1"),
      class = "factor"
    ),
    counts = c(8L, 3L, 4L, 3L, 12L, 2L),
    perc = c(
      72.7272727272727, 27.2727272727273,
      57.1428571428571, 42.8571428571429,
      85.7142857142857, 14.2857142857143
    ),
    `0` = c(1, 2, 3, 4, 5, 6)
  ),
  class = "data.frame",
  row.names = c(NA, -6L)
)

Task 1: Replace Cross-Row Duplicates in a Specified Column with NA

If you want to replace repeated values in a column (like condition where 4,6,8 each appear twice) with NA, you can use base R or the tidyverse's dplyr package—both approaches work well.

Base R Approach

Super straightforward with the duplicated() function, which flags repeated values after their first occurrence:

# Target the 'condition' column: replace duplicates with NA
df$condition[duplicated(df$condition)] <- NA

Result for the condition column:

[1] 4 NA 6 NA 8 NA

Tidyverse (dplyr) Approach

Use lag() to compare each row to the one before it, then replace matches with NA:

library(dplyr)

df <- df %>%
  mutate(condition = if_else(condition == lag(condition), NA_real_, condition))

NA_real_ ensures we keep the numeric type of the condition column intact—no accidental type changes here.

Task 2: Generate NA Every Other Row in a Specified Column

To set every other row (either even or odd-indexed) to NA, logical indexing is your friend. Let's use the main column as an example.

Set Even Rows to NA

Use c(FALSE, TRUE) to target rows 2, 4, 6, etc.:

# Replace even rows in 'main' column with NA
df$main[c(FALSE, TRUE)] <- NA

Result for the main column:

[1] 1 0 0
Levels: 0 1

Set Odd Rows to NA

If you want to target rows 1, 3, 5 instead, flip the logical vector to c(TRUE, FALSE):

# Replace odd rows in 'main' column with NA
df$main[c(TRUE, FALSE)] <- NA

Result:

[1] 0 1 1
Levels: 0 1

You can swap out the column name (e.g., counts, perc) and adjust the logical vector to fit your exact needs.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:13:49