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

如何调整R语言输出,使重复edta_code样本连续排列

调整输出让重复EDTA代码连续显示

需要调整现有代码的输出,使相同的edta_code连续排列,尽量少改动现有代码。以下是数据、现有代码、当前输出及期望输出:

数据定义

df1 <- structure(list(
  subject_id = c("191-5467", "191-6784", "191-3457", "191-0987", "191-1245", "191-1945", "191-3000", "191-5000", "191-9600", "191-0001", "191-0002", "191-0003", "191-0004", "191-5000"), 
  edta_collect = c(1,0,1,1,1,0,0,1,1,1,1,1,1,1),
  edta_code = c("EDTA45", NA, "EDTA20", "EDTA66", "EDTA12", NA, NA,"EDTA19", "EDTA03", "EDTA66", "EDTA10", "EDTA03", "EDTA30", "EDTA20"), 
  ipv = c(1,1,4,6,3,2,5,1,3,4,5,2), 
  epds = c(13, 12, 10, 8, 30, 33, 20, 26, 12, 10, 11, 15, 1, 13, 40)), 
  class = "data.frame", row.names = c(NA, -14L))

现有代码

edta <- df1 %>%
  select(subject_id, edta_collect, edta_code) %>%
  filter(edta_collect == 1)

n_occur_edta <- data.frame(table(edta$edta_code))

edta[edta$edta_code %in% n_occur_edta$Var1[n_occur_edta$Freq > 1], ]

当前输出

subject_id edta_collect edta_code
2    191-3457            1    EDTA20
3    191-0987            1    EDTA66
6    191-9600            1    EDTA03
7    191-0001            1    EDTA66
9    191-0003            1    EDTA03
11   191-5000            1    EDTA20

期望输出

subject_id edta_collect edta_code
2    191-3457            1    EDTA20
11   191-5000            1    EDTA20
3    191-0987            1    EDTA66
7    191-0001            1    EDTA66
6    191-9600            1    EDTA03
9    191-0003            1    EDTA03

解决方案

只需要在现有代码的最后一步添加排序逻辑即可实现需求,改动极小:

基于dplyr的写法(与原代码风格一致)

edta <- df1 %>%
  select(subject_id, edta_collect, edta_code) %>%
  filter(edta_collect == 1)

n_occur_edta <- data.frame(table(edta$edta_code))

# 新增arrange排序,让相同edta_code连续排列
edta[edta$edta_code %in% n_occur_edta$Var1[n_occur_edta$Freq > 1], ] %>% 
  arrange(edta_code)

基于base R的写法

如果偏好原生R语法,也可以用order()函数调整排序:

edta <- df1 %>%
  select(subject_id, edta_collect, edta_code) %>%
  filter(edta_collect == 1)

n_occur_edta <- data.frame(table(edta$edta_code))

result <- edta[edta$edta_code %in% n_occur_edta$Var1[n_occur_edta$Freq > 1], ]
# 按edta_code排序
result[order(result$edta_code), ]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 03:32:02