我有一个向量,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
对于
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")
但是......我认为这不是你所需要的,有几个原因:
CongruentCodes
的长度大于 1,所以我认为你需要 %in%
,请参阅
test=
(第一个)参数ifelse
需要一个logical
返回,我猜你的$BinNumb
列是整数/数字,不符合逻辑,所以这不完全是我们想要的;Congruency
列的所有值,而不仅仅是匹配子集条件的值
which
可以并且通常会返回与原始数据不同的长度,并且仅包含那些匹配的元素(并且对不匹配的元素不执行任何操作),删除 which(
和 )
你会得到什么返回一个与数据长度相同的 logical
向量(这就是我们需要的);这类似于
我认为您只需要
$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(. == .)
一起使用,并且就像. == .
一样,它的第二个参数接受逻辑和整数(索引)参数。)