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

如何使用键向量将R语言数据框重编码为0和1

如何用键向量将数据框重编码为0和1?

嘿,我来帮你搞定这个重编码需求!首先先明确下逻辑:应该是数据框中每个位置的元素,和key对应位置的值相等时编码为1,不等则为0对吧?下面给你几种简单的实现方法:

首先先把你的原始数据用R代码还原出来,方便直接运行:

# 你的键向量
key <- c(2,1,3,2,3,3,3,1,1,3,1,3,3,1,2,3,1,2,2,3,1,3,2,2,1,3,2,2,2,3)

# 你的数据框
df <- data.frame(
  V1 = c(1,1,2), V2 = c(1,1,1), V3 = c(1,3,1), V4 = c(4,2,2), V5 = c(3,3,1),
  V6 = c(4,2,3), V7 = c(3,1,3), V8 = c(1,1,1), V9 = c(2,2,2), V10 = c(2,1,1),
  V11 = c(4,3,1), V12 = c(2,2,2), V13 = c(2,2,3), V14 = c(1,3,1), V15 = c(2,1,1),
  V16 = c(3,2,3), V17 = c(2,1,1), V18 = c(4,4,2), V19 = c(2,1,2), V20 = c(2,2,3),
  V21 = c(1,2,1), V22 = c(2,4,3), V23 = c(3,3,2), V24 = c(2,4,2), V25 = c(1,1,1),
  V26 = c(4,3,3), V27 = c(2,3,2), V28 = c(1,4,3), V29 = c(4,4,2), V30 = c(3,4,3)
)

方法1:基础R原生实现(无需额外包)

这种方法用基础R就能搞定,核心是利用矩阵的广播比较:

# 把数据框转成矩阵,和重复后的key做元素级比较,再转成整数1/0,最后转回数据框
encoded_df <- as.data.frame(
  matrix(
    as.integer(as.matrix(df) == rep(key, each = nrow(df))),
    nrow = nrow(df),
    dimnames = list(rownames(df), colnames(df))
  )
)

简单解释下:rep(key, each = nrow(df))会把key重复3次(因为你的数据框有3行),和数据框转成的矩阵做逐元素比较,得到的逻辑值(TRUE/FALSE)转成整数就是1/0,最后再转回数据框,还保留了原来的行名列名。

如果你习惯用apply函数,也可以这么写:

# 对数据框的每一行,和key比较后转成整数,再转置调整结构
encoded_df <- as.data.frame(t(apply(df, 1, function(row) as.integer(row == key))))
colnames(encoded_df) <- colnames(df)

方法2:tidyverse风格实现(dplyr+purrr)

如果你平时常用tidyverse的工具包,这个写法会更符合你的习惯:

library(dplyr)
library(purrr)
library(stringr)

encoded_df <- df %>%
  imap_dfc(function(col_data, col_name) {
    # 从列名(比如V1)提取对应的key位置索引
    col_index <- as.integer(str_remove(col_name, "V"))
    # 比较并转成1/0
    as.integer(col_data == key[col_index])
  })

这里imap_dfc会遍历数据框的每一列,同时拿到列数据和列名,通过列名提取对应的key位置,完成比较后组合成新的数据框。

验证结果

比如看第一行的V2:原数据是1,key[2]也是1,所以编码后是1;第一行V1是1,key[1]是2,编码后是0,完全符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:56:52