
我想使用我在下面的代码中包含的逻辑在类别列中获取类别名称.但是,它会中断并产生错误.评级变量是整数.
if (nps$Rating <= 6) {
nps$npsCAT <- "Detractor"
} else if (nps$Rating > 6 & nps$Rating < 9) {
nps$npsCAT <- "Passive"
} else {
nps$npsCAT <- "Promoter"
}
Run Code Online (Sandbox Code Playgroud)
警告消息:在if(nps $ Rating <= 6){:条件长度> 1且仅使用第一个元素
nps <- data.frame(Rating=c(1,3,4,7,8,9,2,10,10));
nps$Category <- ifelse(nps$Rating<=6,'Detractor',ifelse(nps$Rating>6 & nps$Rating<9,'Passive','Promoter'));
nps;
## Rating Category
## 1 1 Detractor
## 2 3 Detractor
## 3 4 Detractor
## 4 7 Passive
## 5 8 Passive
## 6 9 Promoter
## 7 2 Detractor
## 8 10 Promoter
## 9 10 Promoter
Run Code Online (Sandbox Code Playgroud)
您收到该警告消息的原因是因为if表达式需要使用单元素向量作为其参数,并且表达式nps$Rating <= 6是LHS长度为9且RHS长度为1的向量化比较,因此表达式的结果将是是一个长度为9的逻辑向量.
考虑:
if (T) 1;
## [1] 1
if (F) 2;
if (c(T,F)) 3;
## [1] 3
## Warning message:
## In if (c(T, F)) 3 :
## the condition has length > 1 and only the first element will be used
if (c(F,T)) 4;
## Warning message:
## In if (c(F, T)) 4 :
## the condition has length > 1 and only the first element will be used
ifelse(c(F,T,T,F),5,6);
## [1] 6 5 5 6
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
106 次 |
| 最近记录: |