I am new to R and I need new help filling an existing column based on conditions in two others.
The dataframe is called A.
If the columns box=6 AND document = 75 then size= big.
I have tried multiple options I found online but R keeps making them out to be an error. I would appreciate it if someone can give me the code line. Thank you
CodePudding user response:
Without more details (i.e. a reproducible example) it is difficult to know whether this answers your question or not, but here is a potential solution:
set.seed(3)
A <- data.frame(box = sample(5:7, size = 50, replace = TRUE),
document = sample(74:76, size = 50, replace = TRUE))
A$size <- ifelse(A$box == 6 & A$document == 75, "big", "other")
head(A, 10)
#> box document size
#> 1 5 76 other
#> 2 6 76 other
#> 3 7 75 other
#> 4 6 75 big
#> 5 7 74 other
#> 6 7 76 other
#> 7 6 75 big
#> 8 7 74 other
#> 9 5 75 other
#> 10 6 74 other
Another potential solution is to use case_when()
from the dplyr package:
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
A <- data.frame(box = sample(5:7, size = 50, replace = TRUE),
document = sample(74:76, size = 50, replace = TRUE))
A %>%
mutate(size = case_when(box == 6 & document == 75 ~ "big",
box < 6 & document < 75 ~ "small",
document < 75 ~ "medium",
TRUE ~ "other"))
#> box document size
#> 1 6 75 big
#> 2 6 74 medium
#> 3 7 76 other
#> 4 5 75 other
#> 5 6 76 other
#> 6 5 75 other
#> 7 6 76 other
#> 8 5 74 small
#> 9 5 74 small
#> 10 6 74 medium
#> ...
Created on 2021-11-08 by the reprex package (v2.0.1)