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

R语言使用Tidyverse检查列值是否存在于其他列并替换值

tidyverse实现方案

前置准备

加载依赖包,构造题目示例数据:

library(tidyverse)

df <- diag(1:8) %>% 
  as_tibble() %>%  
  mutate(A = c(10, 5, 11, 4, 6, 9, 65, 8))

需求1:新增列判断A列值是否存在于V1-V8列的取值集合中

直接通过%in%做值匹配即可,代码如下:

df_result1 <- df %>% 
  mutate(result = A %in% unlist(select(., V1:V8)))

运行结果和预期完全一致:

# A tibble: 8 × 10
     V1    V2    V3    V4    V5    V6    V7    V8     A result
  <int> <int> <int> <int> <int> <int> <int> <int> <dbl> <lgl>
1     1     0     0     0     0     0     0     0    10 FALSE
2     0     2     0     0     0     0     0     0     5 TRUE 
3     0     0     3     0     0     0     0     0    11 FALSE
4     0     0     0     4     0     0     0     0     4 TRUE 
5     0     0     0     0     5     0     0     0     6 TRUE 
6     0     0     0     0     0     6     0     0     9 FALSE
7     0     0     0     0     0     0     7     0    65 FALSE
8     0     0     0     0     0     0     0     8     8 TRUE 

需求2:将A列替换为对应行V1-V8列的非零值

通用写法(兼容每行多个非零值场景)

按行遍历提取V1-V8中的非零值赋值给A列:

df_result2 <- df %>% 
  rowwise() %>% 
  mutate(A = c_across(V1:V8)[c_across(V1:V8) != 0]) %>% 
  ungroup()

高效向量化写法(适配当前对角矩阵场景,每行仅1个非零值)

不需要行遍历,直接按行求和即可得到唯一非零值,性能更好:

df_result2 <- df %>% 
  mutate(A = rowSums(across(V1:V8)))

运行结果和预期完全一致:

# A tibble: 8 × 9
     V1    V2    V3    V4    V5    V6    V7    V8     A
  <int> <int> <int> <int> <int> <int> <int> <int> <int>
1     1     0     0     0     0     0     0     0     1
2     0     2     0     0     0     0     0     0     2
3     0     0     3     0     0     0     0     0     3
4     0     0     0     4     0     0     0     0     4
5     0     0     0     0     5     0     0     0     5
6     0     0     0     0     0     6     0     0     6
7     0     0     0     0     0     0     7     0     7
8     0     0     0     0     0     0     0     8     8

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 09:15:46