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

如何使用R移除所有列值相同或全为空的行?

解决方案

可以通过以下两种方式实现需求:

方法一:基础R实现

# 加载数据集(添加stringsAsFactors=FALSE避免自动转为因子)
df <- data.frame(players=c('', 'Uncredited', 'C', 'D', 'E'),
                 assists=c("", "Uncredited", 4, 4, 3),
                 ratings=c("", "Uncredited", 4, 7, ""),
                 stringsAsFactors = FALSE)

# 筛选保留的行:排除全空行 + 排除所有列值相同的行
clean_df <- df[!((rowSums(df == "") == ncol(df)) | apply(df, 1, function(x) length(unique(x)) == 1)), ]

# 查看结果
clean_df

方法二:dplyr包实现

如果你习惯使用tidyverse工具链,也可以用dplyr简化操作:

library(dplyr)

df <- data.frame(players=c('', 'Uncredited', 'C', 'D', 'E'),
                 assists=c("", "Uncredited", 4, 4, 3),
                 ratings=c("", "Uncredited", 4, 7, ""),
                 stringsAsFactors = FALSE)

clean_df <- df %>%
  filter(
    # 排除全空行
    rowSums(. == "") != ncol(.),
    # 排除所有列值相同的行
    !apply(., 1, function(x) length(unique(x)) == 1)
  )

clean_df

代码逻辑说明

  1. 排除全空行:rowSums(df == "") == ncol(df) 判断每行是否所有元素都是空字符串"",取反后保留非全空行。
  2. 排除所有列值相同的行:apply(df, 1, function(x) length(unique(x)) == 1) 逐行检查该行所有元素的唯一值数量是否为1(即所有值完全一致),取反后保留值不全部相同的行。
  3. 两个条件用|(逻辑或)连接,整体取反后筛选出符合要求的行。

匹配期望输出格式的补充操作

如果需要将assists列转换为数值型以匹配你展示的输出格式,可以在清洗后执行:

# 基础R方式
clean_df$assists <- as.numeric(clean_df$assists)

# dplyr方式
clean_df <- clean_df %>% mutate(assists = as.numeric(assists))

最终得到的结果如下:

players assists ratings
3       C       4       4
4       D       4       7
5       E       3        

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 17:55:18