[英]R Use Dplyr to create a column that contain 1 of 6 possible values based on the value of 5 other columns
in R, I am trying to create one column called model where the value depends on the value of up to 5 other columns.在 R 中,我试图创建一个名为 model 的列,其中的值取决于最多 5 个其他列的值。
The columns are Sport, Car, SUV, Wagon, Minivan, Pickup.列是运动、汽车、SUV、旅行车、小型货车、皮卡。 These 5 columns have a value of 1 if it is a member of that group otherwise it has a 0. I would like to create one column called model that would equal 1 if Sport = 1,2 if SUV = 1, 3 if Wagon =1, 4 if Minivan = 1 , 5 if Pickup = 1 otherwise if all 5 columns equal 0 then model would = 0. I tried it using case statements and mutate using dplyr
如果这 5 列是该组的成员,则其值为 1,否则为 0。我想创建一个名为 model 的列,如果 Sport = 1,2 如果 SUV = 1,则等于 1,如果 Wagon = 则等于 3 1, 4 if Minivan = 1 , 5 if Pickup = 1 否则如果所有 5 列都等于 0 那么模型将 = 0。我尝试使用 case 语句并使用 dplyr 进行变异
cars %>%
mutate(model == case_when(Sport == 1, ~ '1'
,case_when(SUV == 1, ~ '2'
,case_when(Wagon == 1, ~'3'
,case_when(Minivan == 1, ~'4'
,case_when(Pickup == 1, ~ '5'
,TRUE ~ 0))))))
but I got this error:但我收到了这个错误:
> error: Problem with `mutate()` input `..1`.
i `..1 = ==...`.
x Case 1 (`Pickup == 1`) must be a two-sided formula, not a logical vector.
I have included a link to the file below.我已经包含了指向以下文件的链接。 [04cars.csv file]
[04cars.csv 文件]
You don't nest case_when
statements, You just pass all your expressions to one call to case_when
您不嵌套
case_when
语句,您只需将所有表达式传递给对case_when
一次调用
cars %>%
mutate(model = case_when(
Sport == 1 ~ '1',
SUV == 1 ~ '2',
Wagon == 1 ~'3',
Minivan == 1 ~'4',
Pickup == 1 ~ '5'
TRUE ~ 0))
One the first matching condition for each value will be used.将使用每个值的第一个匹配条件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.