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

如何在R语言中根据指定列条件删除DataFrame中特定行的NA值

Solution for Filtering Your R DataFrame

Hey there! Let's get your DataFrame sorted exactly how you want it. The key here is to only remove rows where bs_Scores is "bs_24" AND value is NA, while keeping all other NA values for the other categories.

First, let's replicate your original data so we can work with it:

# Create the original DataFrame
df <- data.frame(
  bs_Scores = c("bs_0", "bs_1", "bs_12", "bs_24", "bs_0", "bs_1", "bs_12", "bs_24", "bs_0", "bs_1", "bs_12", "bs_24", "bs_0"),
  value = c(16.7, 41.7, 33.3, NA, 25, 41.7, NA, 0, 16.7, 41.7, 16.7, 16.7, NA)
)

Using dplyr (tidyverse approach)

If you use the tidyverse, the filter() function makes this straightforward. We'll keep rows where either bs_Scores isn't "bs_24", OR if it is "bs_24", then value isn't NA:

library(dplyr)

filtered_df <- df %>%
  filter(bs_Scores != "bs_24" | !is.na(value))

Using Base R

If you prefer base R, here's the equivalent code using logical indexing:

filtered_df <- df[!(df$bs_Scores == "bs_24" & is.na(df$value)), ]

Result

Both methods will give you the exact output you're looking for:

bs_Scores value
1       bs_0  16.7
2       bs_1  41.7
3      bs_12  33.3
5       bs_0  25.0
6       bs_1  41.7
7      bs_12    NA
8      bs_24   0.0
9       bs_0  16.7
10      bs_1  41.7
11     bs_12  16.7
12     bs_24  16.7
13      bs_0    NA

This removes only the row where bs_Scores is "bs_24" and value is NA, while preserving all other NA values in bs_0, bs_1, and bs_12.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 18:52:35