本文介绍了为什么R中的()在一个案例中进行向量运算而在另一个案例中没有?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有下表:
> head(datalist[[5]])
X5CO X5CS X5CD X5CSD
1 24.87769 24.31233 26.84647 34.3316
2 24.74026 24.31233 26.84647 34.3316
3 24.45217 24.31233 26.84647 34.3316
10 24.87769 24.31233 26.15139 34.3316
11 24.74026 24.31233 26.15139 34.3316
12 24.45217 24.31233 26.15139 34.3316
我需要使用每一行作为变量值来应用以下表达式。所以我正在使用with()函数。这适用于2嵌套ifelse,但是当我添加第三个ifelse()时它不再起作用。自己看看:
I need to apply the following expression using every row as variable values. So I'm using with() function. This is working well with 2 nested ifelse, but when I add a third ifelse() it doesn't work anymore. See by yourself :
> with( head(datalist[[5]]),{
+ cCO=get(paste("X", 5,"CO",sep=""))
+ cCS=get(paste("X", 5,"CS",sep=""))
+ cCD=get(paste("X", 5,"CD",sep=""))
+ cCSD=get(paste("X", 5,"CSD",sep=""))
+ ifelse( (cCS-cCO) > 0, 1, #1st consequent
+ ifelse ( (cCD-cCO) > 0, 2, # 2nd
+ 5) ) } ) # default
[1] 2 2 2 2 2 2
只有2个嵌套循环,结果是[1] 2 2 2 2 2 2,这就是我想要的。但是当我添加第三个条件时它不再起作用了:
With only 2 nested loops the result is [1] 2 2 2 2 2 2 and it is what I want. However when I add a third condition it doesn't work anymore :
> with( head(datalist[[5]]),{
+ cCO=get(paste("X", 5,"CO",sep=""))
+ cCS=get(paste("X", 5,"CS",sep=""))
+ cCD=get(paste("X", 5,"CD",sep=""))
+ cCSD=get(paste("X", 5,"CSD",sep=""))
+ ifelse( (cCS-cCO)>0 && (cCD-cCO) > 0, 3, #1st consequent
+ ifelse( (cCS-cCO) > 0, 1, #2nd consequent
+ ifelse ( (cCD-cCO) > 0, 2, # 3rd
+ 5) ) ) } ) # default
[1] 2
为什么这样做?
推荐答案
以下是一些更好的代码:
Here is some nicer code:
DF <- read.table(text="X5CO X5CS X5CD X5CSD
1 24.87769 24.31233 26.84647 34.3316
2 24.74026 24.31233 26.84647 34.3316
3 24.45217 24.31233 26.84647 34.3316
10 24.87769 24.31233 26.15139 34.3316
11 24.74026 24.31233 26.15139 34.3316
12 24.45217 24.31233 26.15139 34.3316",header=TRUE)
#clean-up column names
names(DF) <- gsub("X5","c",names(DF))
#logicals get converted to numerics, when doing calculations with them
with(DF,(cCO<cCS) + (cCO<cCD)*2 + (cCO>=cCS & cCO>=cCD)*5)
#[1] 2 2 2 2 2 2
这篇关于为什么R中的()在一个案例中进行向量运算而在另一个案例中没有?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!