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

在R语言中将FRUITS列转换为宽格式的独立布尔列

将数据框FRUITS列转换为Apple/Banana布尔值宽格式

原始数据

Gender  AgeGroup              EAT           FRUITS 
1 Female 30yr_39yr              Yes             Apple           
2 Female 20yr_29yr              Yes             Apple              
3 Female 70yr_80yr              Yes             Apple              
4   Male 50yr_59yr              Yes             Banana              
5 Female 40yr_49yr              Yes             Apple                   
6 Female 70yr_80yr              Yes             Apple               

数据集代码

df <- data.frame(
  Gender = c("Female", "Female", "Female", "Male", "Female", "Female"),
  AgeGroup = c("30yr_39yr", "20yr_29yr", "70yr_80yr", "50yr_59yr", "40yr_49yr", "70yr_80yr"),
  EAT = c("Yes", "Yes", "Yes", "Yes", "Yes", "Yes"),
  FRUITS = c("Apple", "Apple", "Apple", "Banana", "Apple", "Apple")
)

期望输出

Gender AgeGroup       EAT  Apple      Banana 
1 Female 30yr_39yr      Yes  TRUE      FALSE
2 Female 20yr_29yr      Yes  TRUE      FALSE
3 Female 70yr_80yr      Yes  TRUE      FALSE
4   Male 50yr_59yr      Yes  FALSE     TRUE
5 Female 40yr_49yr      Yes  TRUE      FALSE
6 Female 70yr_80yr      Yes  TRUE      FALSE

解决方案

方法1:使用tidyr包(tidyverse生态)

这是最简洁的实现方式,先确保安装并加载tidyr:

# 若未安装包,先执行安装
# install.packages("tidyr")
library(tidyr)

df_wide <- df %>%
  pivot_wider(
    id_cols = c(Gender, AgeGroup, EAT),  # 保留不变的列
    names_from = FRUITS,                 # 用FRUITS的取值作为新列名
    values_from = FRUITS,                # 基于FRUITS列生成值
    values_fn = ~ !is.na(.),             # 存在该水果则标记为TRUE
    values_fill = FALSE                  # 缺失值填充为FALSE
  )

print(df_wide)

方法2:基础R实现(无需额外包)

如果不想加载外部包,可以用基础R的table函数结合矩阵操作:

# 生成每行对应水果的布尔矩阵
fruit_bool <- t(table(df$FRUITS, rownames(df)) == 1)

# 合并矩阵与原数据,移除原FRUITS列
df_wide_base <- cbind(df[, -4], as.data.frame(fruit_bool))

print(df_wide_base)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 08:23:39