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

R语言dataframe长格式转宽格式:按sample生成病毒存在与否0-1标识

R长格式数据转宽格式实现方案

需求:将包含virus、sample、cond三个字段的长表,转换为以virus为行标识、每个sample取值为单独列的宽表,cond字段中Present映射为1,Absent映射为0。


方法1:tidyverse生态实现(推荐,写法简洁)

# 加载依赖包
library(tidyverse)

# 数据转换逻辑
df.out <- df %>%
  # 先将cond文本转换为0/1数值
  mutate(cond = ifelse(cond == "Present", 1, 0)) %>%
  # 长表转宽表:列名取自sample字段,值取转换后的cond
  pivot_wider(names_from = sample, values_from = cond)

方法2:base R实现(无需安装额外依赖包)

# 转换cond为0/1数值
df$cond <- ifelse(df$cond == "Present", 1, 0)
# 调用reshape做长转宽
df.out <- reshape(df, idvar = "virus", timevar = "sample", direction = "wide")
# 清理列名默认前缀
colnames(df.out) <- gsub("cond\\.", "", colnames(df.out))
# 重置行号
rownames(df.out) <- NULL

输出验证

两种方法运行后打印df.out均可得到目标结果:

> df.out
   virus A B
1 virusA 1 0
2 virusB 1 1
3 virusC 0 1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 09:27:00