使用mtcars
包中的datasets
,我想添加一个从mtcars$mpg
创建的添加列,以便:
If mtcars$mpg >=15 and <19 then "Good"
If mtcars$mpg >=19 and <27 then "Average"
If mtcars$mpg >=27 then "Bad"
答案 0 :(得分:1)
您可以使用explicit
struct X {
explicit operator double() const { return 3.14; }
};
double y = static_cast<double>(X{}); // ok;
double z = X{}; // error
答案 1 :(得分:0)
如果你想要tidyverse解决方案,试试这个:
library(tidyverse)
df <- as_tibble(mtcars)
df %>%
mutate(mpg_quality = case_when(mpg >= 15 & mpg < 19 ~ "good",
mpg >= 19 & mpg < 27 ~ "average",
mpg >= 27 ~ "bad"))
这给了我们:
# A tibble: 32 x 12
mpg cyl disp hp drat wt qsec vs am gear carb mpg_quality
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <chr>
1 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4 average
2 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4 average
3 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1 average
4 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1 average
5 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2 good
6 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1 good
7 14.3 8 360.0 245 3.21 3.570 15.84 0 0 3 4 <NA>
8 24.4 4 146.7 62 3.69 3.190 20.00 1 0 4 2 average
9 22.8 4 140.8 95 3.92 3.150 22.90 1 0 4 2 average
10 19.2 6 167.6 123 3.92 3.440 18.30 1 0 4 4 average
# ... with 22 more rows
df <- as_tibble(mtcars)
不是必需的,但我喜欢吃,所以我把它包括在内。