【问题标题】:How can I code this indicator matrix without using a loop in R [duplicate]如何在不使用 R 循环的情况下编写此指标矩阵 [重复]
【发布时间】:2019-12-19 16:39:57
【问题描述】:

我有一个由一系列数字给出的因子向量。这些因素也可以在单独的数据集中找到,称为test_settrain_set。以下代码的作用是找到数据集中的因子在因子向量中匹配的位置,并将 1 放在矩阵的位置。将此矩阵compound_test 乘以test_set$Compound 应该得到compare_comp

test_set <- data.frame(Compound=letters[sample(1:3,10,replace = TRUE)])
train_set <- data.frame(Compound=letters[sample(1:3,10,replace = TRUE)])

compare_comp <- letters[1:3]
compound_test <- matrix(0,nrow(test_set),length(compare_comp)) # test indicator matrix
compound_train <-matrix(0,nrow(train_set),length(compare_comp))

for (i in 1:length(compare_comp)){
  compound_test[which(compare_comp[i]==test_set$Compound),i]=1
  compound_train[which(compare_comp[i]==train_set$Compound),i]=1}

R 中是否有一个函数可以让我创建相同的东西而无需 for 循环?我试过model.matrix(~Compound,data=test_set),但由于参考级别,这不包括列,并且还会产生不需要的列名

【问题讨论】:

    标签: r for-loop matrix indicator


    【解决方案1】:

    更简单的选择是model.matrix 来自base R

    model.matrix(~ Compound-1, train_set)
    model.matrix(~ Compound-1, test_set)
    

    如果我们cbind带有一系列行,也可以使用table

    table(cbind(nr = seq_len(nrow(train_set)), train_set))
    

    【讨论】:

      猜你喜欢
      • 2020-04-11
      • 2021-06-08
      • 2017-09-29
      • 2020-05-12
      • 1970-01-01
      • 1970-01-01
      • 2018-01-30
      • 1970-01-01
      • 2014-12-03
      相关资源
      最近更新 更多