假设small_vehicle和large_vehicle是互斥且穷举的类别,我们可以在没有if/then逻辑的情况下创建Combined,如下所示。
small_vehicle <- c(1,0,0,1,1,1,0)
large_vehicle <- c(0,1,1,0,0,0,1)
TRIdata <- data.frame(small_vehicle,large_vehicle)
TRIdata$Combined <- 2*TRIdata$large_vehicle + small_vehicle
TRIdata
...和输出:
> TRIdata
small_vehicle large_vehicle Combined
1 1 0 1
2 0 1 2
3 0 1 2
4 1 0 1
5 1 0 1
6 1 0 1
7 0 1 2
>
替代方法
我们可以用ifelse() 做同样的事情。
# alternate approach
small_vehicle <- c(1,0,0,1,1,1,0)
large_vehicle <- c(0,1,1,0,0,0,1)
TRIdata <- data.frame(small_vehicle,large_vehicle)
TRIdata$Combined <- ifelse(TRIdata$small_vehicle == 1,1,2)
TRIdata
...和输出。
> TRIdata
small_vehicle large_vehicle Combined
1 1 0 1
2 0 1 2
3 0 1 2
4 1 0 1
5 1 0 1
6 1 0 1
7 0 1 2
>
为什么原始代码不起作用?
我将使用以下代码说明我对原始帖子的评论。我们将更正原始版本中的 = 与 == 错误,然后尝试运行它。
# original code with my sample data
small_vehicle <- c(1,0,0,1,1,1,0)
large_vehicle <- c(0,1,1,0,0,0,1)
TRIdata <- data.frame(Small_Vehicle = small_vehicle,
Large_Vehicle = large_vehicle)
if (TRIdata$Small_Vehicle == 1) {
TRIdata$Combined <- 1
} else {
if (TRIdata$Large_Vehicle == 1) {
TRIdata$Combined <- 2
} else {
TRIdata$Combined <- NA
}
}
...产生以下警告:
Warning message:
In if (TRIdata$Small_Vehicle == 1) { :
the condition has length > 1 and only the first element will be used
>
当我们打印结果时,我们观察到 R 将 TRIdata$Small_Vehicle 的第一个元素评估为 TRUE,并将值 1 分配给 TRIdata$Combined 中的每个元素。
> TRIdata
Small_Vehicle Large_Vehicle Combined
1 1 0 1
2 0 1 1
3 0 1 1
4 1 0 1
5 1 0 1
6 1 0 1
7 0 1 1
>