尝试根据索引向量替换向量中的项目

问题描述 投票:0回答:1

我有一个向量,SingleMeans$BinNumb,看起来像这样:

rSingleMeans$BinNumb <- c(1,5,6,101,106,201,206,3,6,202,211,207,4,6,105,101)

我想将向量中与“全等代码”中列出的代码匹配的所有项目编码为“全等”

CongruentCodes = c(101,102,103,104,109,110,111,112,201,202,203,204,209,210,211,212)

这就是我正在尝试做的:

SingleMean$Congruency<- ifelse(SingleMean$BinNumb[which(SingleMean$BinNumb == CongruentCodes)],"Congruent","Incongruent")

但是它吐出这个错误并返回 null:

Warning message:
In SingleMean$BinNumb == CongruentCodes :
  longer object length is not a multiple of shorter object length
r vector
1个回答
0
投票

对于

data.frame
,作业的 LHS 和 RHS 必须具有相同的长度向量。如果您对一侧进行子集化,则必须对另一侧进行相同的子集化。

举个例子,

# this is wrong
SingleMean$Congruency <- 
  ifelse(
    SingleMean$BinNumb[which(SingleMean$BinNumb == CongruentCodes)],
    "Congruent", "Incongruent")

除非

which(.)
返回相同的长度,否则我们没有相同的边。解决这个问题的一个字面步骤是:

# this is likely wrong but may not error
SingleMean$Congruency[which(SingleMean$BinNumb == CongruentCodes)] <- 
  ifelse(
    SingleMean$BinNumb[which(SingleMean$BinNumb == CongruentCodes)],
    "Congruent", "Incongruent")

但是......我认为这不是你所需要的,有几个原因:

我认为您只需要

$BinNum %in% CongruentCodes
中的
test
,它将根据条件返回
yes=
no=
值之一。

SingleMean$Congruency <- 
  ifelse(
    SingleMean$BinNumb %in% CongruentCodes,
    "Congruent", "Incongruent")

使用

which
的时间可能包括这样的内容(尽管我更喜欢上面的
ifelse
):

# I don't think this is the best way to do it
SingleMean$Congruency <- "Incongruent"
SingleMean$Congruency <- 
  replace(SingleMean$Congruency,
          which(SingleMean$BinNumb %in% CongruentCodes),
          "Congruent")

那个代码可以与

which(. == .)
一起使用,并且就像
. == .
一样,它的第二个参数接受逻辑和整数(索引)参数。)

© www.soinside.com 2019 - 2024. All rights reserved.