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

如何使用Tidy/Dplyr移除数据框中填充数达指定值的行或列?

使用dplyr移除指定填充数量的列和行

移除非零值数量≤3的列

假设"填充单元格"指非零值,我们可以用dplyr的select()结合where()筛选列,保留非零值数量超过3的列:

library(dplyr)

# 示例数据
df <- structure(list(Site = c("A", "B", "C", "D", "E", "F", "G", "H",  "I"), 
                     X1= c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 3L), 
                     X2 = c(0L,  0L, 0L, 0L, 0L, 0L, 0L, 10L, 0L), 
                     X3 = c(0L, 0L, 0L, 0L,  0L, 3L, 6L, 0L, 0L), 
                     X4 = c(0L, 9L, 4L, 1L, 8L, 6L, 0L,  0L, 0L), 
                     X5 = c(6L, 5L, 2L, 5L, 1L, 5L, 2L, 0L, 0L)), 
                class = "data.frame", row.names = c(NA, -9L))

# 筛选列:保留非零值>3的列,同时保留Site列
df_cols_cleaned <- df %>%
  select(Site, where(~ sum(.x != 0) > 3))

# 输出结果
df_cols_cleaned

运行后会删除X1、X2、X3列,因为它们的非零值数量分别为1、1、2,均≤3。

移除填充列数达指定值的行

要移除行中非零值列数等于指定值的行,用filter()结合rowSums()和across()实现:

# 指定要移除的非零值列数
target <- 1

# 移除对应行(排除Site列的字符型数据)
df_rows_cleaned <- df %>%
  filter(rowSums(across(where(is.numeric), ~ .x != 0)) != target)

# 输出结果
df_rows_cleaned

上述代码会移除原数据中的H、I行,因为这两行各只有1个非零值。若要移除其他数量的行,修改target即可(比如target=0移除全零行)。

同时处理列和行

如果需要一次性完成列筛选和行筛选:

df_final <- df %>%
  select(Site, where(~ sum(.x != 0) > 3)) %>%
  filter(rowSums(across(where(is.numeric), ~ .x != 0)) != 0) # 移除无填充值的行

df_final

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 19:47:53