All the cleaning thresholds live here so you can change a decision in one place and re-knit. The defaults were chosen after profiling the raw data (see Section 2).
input_file <- "OriginalDataset_ResidentialRentalPrice.csv"
output_file <- "CleanedDataset_ResidentialRentalPrice.csv"
# Plausible ranges for the two core variables (rows outside are DROPPED)
rent_min <- 200 # RM/month. Values below this (e.g. RM 70, RM 80) are data-entry errors
rent_max <- 30000 # RM/month. There is a gap between ~18,500 and 45,000+; the larger
# values look like sale prices (e.g. RM 2,400,000) rather than rents
size_min <- 100 # sq.ft. Values of 1, 5, ... are errors
size_max <- 10000 # sq.ft. Removes 99,999,999 and 48,010
# Implausible counts (set to NA, row is KEPT)
max_rooms <- 8
max_parking <- 6
year_min <- 1950
year_max <- 2030
# Rent per sq.ft. outside this band is FLAGGED (not removed) for you to review
psf_low <- 0.3
psf_high <- 10
# TRUE = treat missing `parking` as 0 bays
# FALSE = keep as NA (safer; a `parking_missing` flag is always created)
impute_parking_zero <- FALSE
# Keeps a running count of rows after each step
cleaning_log <- tibble(step = character(), rows = integer())
log_step <- function(label, data) {
cleaning_log <<- add_row(cleaning_log, step = label, rows = nrow(data))
data
}
ads_id is an identifier, not a number, and
rooms is mixed text ("3", "3.0",
"More than 10"), so both are read as text.
raw <- read_csv(
input_file,
col_types = cols(.default = col_guess(),
ads_id = col_character(),
rooms = col_character()),
na = c("", "NA", "N/A", "null", "NULL")
)
cleaning_log <- tibble(step = "Raw data", rows = nrow(raw))
glimpse(raw)
## Rows: 19,991
## Columns: 14
## $ ads_id <chr> "100323185", "100203973", "100323128", "10019176…
## $ prop_name <chr> "The Hipster @ Taman Desa", "Segar Courts", "Pan…
## $ completion_year <dbl> 2022, NA, NA, 2020, NA, NA, NA, 2018, 2014, NA, …
## $ monthly_rent <chr> "RM 4 200 per month", "RM 2 300 per month", "RM …
## $ location <chr> "Kuala Lumpur - Taman Desa", "Kuala Lumpur - Che…
## $ property_type <chr> "Condominium", "Condominium", "Apartment", "Apar…
## $ rooms <chr> "5", "3", "3", "2", "1", "3", "3", "1", "2", "3"…
## $ parking <dbl> 2, 1, NA, 1, 1, 1, 2, 1, 1, 1, NA, 2, 1, 1, NA, …
## $ bathroom <dbl> 6, 2, 2, 2, 1, 2, 2, 1, 1, 2, 2, 2, 1, 2, 2, 2, …
## $ size <chr> "1842 sq.ft.", "1170 sq.ft.", "650 sq.ft.", "743…
## $ furnished <chr> "Fully Furnished", "Partially Furnished", "Fully…
## $ facilities <chr> "Minimart, Gymnasium, Security, Playground, Swim…
## $ additional_facilities <chr> "Air-Cond, Cooking Allowed, Washing Machine", "A…
## $ region <chr> "Kuala Lumpur", "Kuala Lumpur", "Kuala Lumpur", …
# Missing values per column
raw %>%
summarise(across(everything(), ~ sum(is.na(.x)))) %>%
pivot_longer(everything(), names_to = "column", values_to = "n_missing") %>%
mutate(pct_missing = round(100 * n_missing / nrow(raw), 1)) %>%
arrange(desc(n_missing))
tibble(
exact_duplicate_rows = sum(duplicated(raw)),
repeated_ads_id = sum(duplicated(raw$ads_id))
)
Known problems found while profiling:
monthly_rent is text such as
"RM 4 200 per month" (space as thousands separator).size is text such as "1842 sq.ft.".rooms mixes "3" and "3.0",
and contains "More than 10".facilities contains stray tokens 10,
11, 6; additional_facilities has
a blank entry.location is "State - Area", and some areas
are just numbers ("Selangor - 389").prop_name contains emojis, promotional text and curly
apostrophes.ads_id).property_type values
("Houses", "Soho", …).Trim whitespace, squash repeated spaces and turn empty strings into
NA.
df <- raw %>%
mutate(across(where(is.character), ~ na_if(str_squish(.x), ""))) %>%
log_step("After text trimming", .)
df <- df %>%
mutate(
# "RM 4 200 per month" -> 4200 (drop everything that is not a digit)
monthly_rent_rm = as.numeric(str_remove_all(monthly_rent, "[^0-9]")),
# "1842 sq.ft." -> 1842
size_sqft = as.numeric(str_extract(size, "\\d+")),
# "3", "3.0" -> 3 ; "More than 10" -> NA (no leading digit)
rooms = as.integer(str_extract(rooms, "^\\d+")),
parking = as.integer(parking),
bathroom = as.integer(bathroom),
completion_year = as.integer(completion_year)
) %>%
select(-monthly_rent, -size)
summary(select(df, monthly_rent_rm, size_sqft, rooms, parking, bathroom, completion_year))
## monthly_rent_rm size_sqft rooms parking
## Min. : 70 Min. : 1 Min. : 1.00 Min. : 1.000
## 1st Qu.: 1100 1st Qu.: 750 1st Qu.: 2.00 1st Qu.: 1.000
## Median : 1400 Median : 886 Median : 3.00 Median : 1.000
## Mean : 2269 Mean : 5922 Mean : 2.68 Mean : 1.417
## 3rd Qu.: 1800 3rd Qu.: 1044 3rd Qu.: 3.00 3rd Qu.: 2.000
## Max. :2400000 Max. :99999999 Max. :10.00 Max. :10.000
## NAs :2 NAs :8 NAs :5702
## bathroom completion_year
## Min. :1.000 Min. :1977
## 1st Qu.:2.000 1st Qu.:2012
## Median :2.000 Median :2017
## Mean :1.892 Mean :2015
## 3rd Qu.:2.000 3rd Qu.:2020
## Max. :8.000 Max. :2025
## NAs :6 NAs :9185
rooms was stored as "3" in one copy and
"3.0" in another, so duplicates are only exact after the
type conversion above.
# (a) Exact duplicate rows
df <- df %>% distinct() %>% log_step("After removing exact duplicates", .)
# (b) Same ads_id, different content: keep the most complete record
df <- df %>%
mutate(.row = row_number(),
.n_missing = rowSums(is.na(across(everything())))) %>%
group_by(ads_id) %>%
slice_min(.n_missing, n = 1, with_ties = FALSE) %>%
ungroup() %>%
arrange(.row) %>%
select(-.row, -.n_missing) %>%
log_step("After de-duplicating on ads_id", .)
# (c) Informational only: the same listing re-posted under a new ads_id?
# Not removed, because different units in the same building can share all of these values.
df %>%
summarise(possible_reposts = sum(duplicated(select(., -ads_id))))
First, how many rows does each rule affect (before anything is changed)?
df %>%
summarise(
rent_missing = sum(is.na(monthly_rent_rm)),
rent_out_of_range = sum(monthly_rent_rm < rent_min | monthly_rent_rm > rent_max, na.rm = TRUE),
size_out_of_range = sum(size_sqft < size_min | size_sqft > size_max, na.rm = TRUE),
rooms_implausible = sum(rooms > max_rooms, na.rm = TRUE),
parking_implausible = sum(parking > max_parking, na.rm = TRUE),
year_implausible = sum(completion_year < year_min | completion_year > year_max, na.rm = TRUE)
) %>%
pivot_longer(everything(), names_to = "rule", values_to = "rows_affected")
Rows with an invalid rent or size
are dropped (they are the core variables, and we cannot guess the
correct value). Implausible values in the other columns are set to
NA and the row is kept.
df <- df %>%
filter(!is.na(monthly_rent_rm),
between(monthly_rent_rm, rent_min, rent_max),
between(size_sqft, size_min, size_max)) %>%
log_step("After dropping invalid rent / size", .) %>%
mutate(
rooms = case_when(rooms > max_rooms ~ NA_integer_, TRUE ~ rooms),
parking = case_when(parking > max_parking ~ NA_integer_, TRUE ~ parking),
completion_year = case_when(
completion_year < year_min | completion_year > year_max ~ NA_integer_,
TRUE ~ completion_year
)
)
# Flag (do not drop) suspicious rent per sq.ft. for manual review
df <- df %>%
mutate(rent_per_sqft = round(monthly_rent_rm / size_sqft, 2),
flag_rent_psf_outlier = rent_per_sqft < psf_low | rent_per_sqft > psf_high)
df %>%
filter(flag_rent_psf_outlier) %>%
select(ads_id, prop_name, monthly_rent_rm, size_sqft, rent_per_sqft) %>%
arrange(rent_per_sqft)
Decide for yourself whether to remove the flagged rows
(filter(!flag_rent_psf_outlier)). Many are 100 sq.ft. rooms
listed at RM 900 and up, which may be genuine room rentals.
location into state and
areadf <- df %>%
separate(location, into = c("state", "area"), sep = " - ", extra = "merge", fill = "right") %>%
mutate(
# Areas that are only digits ("389", "360") are not real place names
area = if_else(str_detect(area, "^\\d+$"), NA_character_, area)
)
# `region` should duplicate `state`; check before dropping it
stopifnot(all(df$state == df$region, na.rm = TRUE))
df <- select(df, -region)
count(df, state)
# Merge rare property types (< 10 listings) into "Others"
common_types <- names(which(table(df$property_type) >= 10))
df <- df %>%
mutate(
property_type = factor(if_else(property_type %in% common_types, property_type, "Others")),
furnished = factor(furnished,
levels = c("Not Furnished", "Partially Furnished", "Fully Furnished")),
state = factor(state),
# Remove emojis / non-ASCII symbols and promotional clutter in names
prop_name = prop_name %>%
str_replace_all("[\u2018\u2019]", "'") %>%
str_replace_all("[^\\x20-\\x7E]", "") %>%
str_squish() %>%
na_if(""),
# Lower-case key for matching the same building spelled differently
prop_name_key = prop_name %>%
str_to_lower() %>%
str_replace_all("[^a-z0-9]+", " ") %>%
str_squish()
)
count(df, property_type, sort = TRUE)
count(df, furnished)
facilities and additional_facilities are
comma-separated lists. One 0/1 column per facility is far easier to
analyse. A missing list is treated as “none listed” (0).
First check which tokens exist, so nothing is missed:
facility_items <- c("Security", "Parking", "Playground", "Swimming Pool", "Gymnasium", "Lift",
"Minimart", "Barbeque area", "Jogging Track", "Multipurpose hall", "Sauna",
"Tennis Court", "Squash Court", "Club house")
extra_items <- c("Cooking Allowed", "Air-Cond", "Near KTM/LRT", "Washing Machine", "Internet")
unrecognised <- bind_rows(
tibble(col = "facilities",
token = unlist(str_split(na.omit(df$facilities), ",\\s*"))),
tibble(col = "additional_facilities",
token = unlist(str_split(na.omit(df$additional_facilities), ",\\s*")))
) %>%
filter(!token %in% c(facility_items, extra_items)) %>%
count(col, token, sort = TRUE)
unrecognised # expect stray numbers (6, 10, 11): scraping artefacts, ignored below
add_flags <- function(data, col, items, prefix) {
for (item in items) {
new_name <- paste0(prefix, str_replace_all(str_to_lower(item), "[^a-z0-9]+", "_"))
pattern <- paste0("(^|, )", item, "(,|$)")
data[[new_name]] <- as.integer(str_detect(coalesce(data[[col]], ""), pattern))
}
data
}
df <- df %>%
add_flags("facilities", facility_items, "fac_") %>%
add_flags("additional_facilities", extra_items, "add_") %>%
mutate(
n_facilities = rowSums(across(starts_with("fac_"))),
n_additional = rowSums(across(starts_with("add_")))
) %>%
select(-facilities, -additional_facilities)
df <- df %>%
mutate(parking_missing = is.na(parking))
if (impute_parking_zero) {
df <- df %>% mutate(parking = replace_na(parking, 0L))
}
df %>%
select(ads_id, prop_name, completion_year, rooms, parking, bathroom, furnished, area) %>%
summarise(across(everything(), ~ sum(is.na(.x)))) %>%
pivot_longer(everything(), names_to = "column", values_to = "n_missing")
Decisions on missing data:
completion_year (about 46% missing) is kept as
NA. Imputing it would invent information. Drop the column or
analyse only the non-missing subset if you need it.parking is NA for many Flat and
Apartment listings, which probably means “no bay”, but this
is an assumption. Set impute_parking_zero <- TRUE in
Section 0 if you accept it.rooms, bathroom, furnished:
only a handful are missing. Keep as NA, or drop with
drop_na() for modelling.clean <- df %>%
relocate(ads_id, prop_name, prop_name_key, state, area, property_type, furnished,
monthly_rent_rm, size_sqft, rent_per_sqft, rooms, bathroom, parking,
parking_missing, completion_year)
stopifnot(
!anyDuplicated(clean$ads_id),
all(clean$monthly_rent_rm >= rent_min & clean$monthly_rent_rm <= rent_max),
all(clean$size_sqft >= size_min & clean$size_sqft <= size_max)
)
glimpse(clean)
## Rows: 19,886
## Columns: 37
## $ ads_id <chr> "100323185", "100203973", "100323128", "10019176…
## $ prop_name <chr> "The Hipster @ Taman Desa", "Segar Courts", "Pan…
## $ prop_name_key <chr> "the hipster taman desa", "segar courts", "pangs…
## $ state <fct> Kuala Lumpur, Kuala Lumpur, Kuala Lumpur, Kuala …
## $ area <chr> "Taman Desa", "Cheras", "Taman Desa", "Sentul", …
## $ property_type <fct> Condominium, Condominium, Apartment, Apartment, …
## $ furnished <fct> Fully Furnished, Partially Furnished, Fully Furn…
## $ monthly_rent_rm <dbl> 4200, 2300, 1000, 1700, 1299, 1500, 2900, 1550, …
## $ size_sqft <dbl> 1842, 1170, 650, 743, 494, 884, 982, 700, 750, 8…
## $ rent_per_sqft <dbl> 2.28, 1.97, 1.54, 2.29, 2.63, 1.70, 2.95, 2.21, …
## $ rooms <int> 5, 3, 3, 2, 1, 3, 3, 1, 2, 3, 2, 4, 1, 3, 5, 3, …
## $ bathroom <int> 6, 2, 2, 2, 1, 2, 2, 1, 1, 2, 2, 2, 1, 2, 2, 2, …
## $ parking <int> 2, 1, NA, 1, 1, 1, 2, 1, 1, 1, NA, 2, 1, 1, NA, …
## $ parking_missing <lgl> FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, …
## $ completion_year <int> 2022, NA, NA, 2020, NA, NA, NA, 2018, 2014, NA, …
## $ flag_rent_psf_outlier <lgl> FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE,…
## $ fac_security <int> 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, …
## $ fac_parking <int> 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, …
## $ fac_playground <int> 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, …
## $ fac_swimming_pool <int> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, …
## $ fac_gymnasium <int> 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, …
## $ fac_lift <int> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, …
## $ fac_minimart <int> 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 1, …
## $ fac_barbeque_area <int> 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 1, …
## $ fac_jogging_track <int> 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, …
## $ fac_multipurpose_hall <int> 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, …
## $ fac_sauna <int> 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, …
## $ fac_tennis_court <int> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, …
## $ fac_squash_court <int> 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, …
## $ fac_club_house <int> 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, …
## $ add_cooking_allowed <int> 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, …
## $ add_air_cond <int> 1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, …
## $ add_near_ktm_lrt <int> 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, …
## $ add_washing_machine <int> 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 1, …
## $ add_internet <int> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, …
## $ n_facilities <dbl> 10, 9, 4, 8, 11, 6, 10, 7, 5, 6, 7, 9, 13, 11, 3…
## $ n_additional <dbl> 3, 3, 0, 3, 1, 2, 4, 4, 4, 3, 2, 4, 4, 3, 3, 5, …
summary(select(clean, monthly_rent_rm, size_sqft, rent_per_sqft, rooms, bathroom, parking))
## monthly_rent_rm size_sqft rent_per_sqft rooms
## Min. : 200 Min. : 100.0 Min. : 0.13 Min. :1.000
## 1st Qu.: 1100 1st Qu.: 750.0 1st Qu.: 1.25 1st Qu.:2.000
## Median : 1400 Median : 888.0 Median : 1.62 Median :3.000
## Mean : 1612 Mean : 918.8 Mean : 1.82 Mean :2.681
## 3rd Qu.: 1800 3rd Qu.:1044.0 3rd Qu.: 2.16 3rd Qu.:3.000
## Max. :18500 Max. :9001.0 Max. :28.89 Max. :7.000
## NAs :7
## bathroom parking
## Min. :1.000 Min. :1.000
## 1st Qu.:2.000 1st Qu.:1.000
## Median :2.000 Median :1.000
## Mean :1.893 Mean :1.413
## 3rd Qu.:2.000 3rd Qu.:2.000
## Max. :8.000 Max. :6.000
## NAs :2 NAs :5673
cleaning_log %>% mutate(removed_this_step = lag(rows, default = first(rows)) - rows)
bind_rows(
tibble(stage = "Raw",
rent = as.numeric(str_remove_all(raw$monthly_rent, "[^0-9]"))),
tibble(stage = "Cleaned", rent = clean$monthly_rent_rm)
) %>%
filter(!is.na(rent)) %>%
ggplot(aes(rent)) +
geom_histogram(bins = 50) +
scale_x_log10(labels = scales::comma) +
facet_wrap(~ stage, scales = "free_y") +
labs(x = "Monthly rent (RM, log scale)", y = "Listings")
clean %>%
ggplot(aes(fct_reorder(property_type, monthly_rent_rm, median), monthly_rent_rm)) +
geom_boxplot(outlier.alpha = 0.3) +
coord_flip() +
facet_wrap(~ state) +
labs(x = NULL, y = "Monthly rent (RM)")
write_csv(clean, output_file)
cat("Saved", nrow(clean), "rows and", ncol(clean), "columns to", output_file)
## Saved 19886 rows and 37 columns to CleanedDataset_ResidentialRentalPrice.csv
| Column | Description |
|---|---|
ads_id |
Listing ID (text, unique) |
prop_name, prop_name_key |
Cleaned property name; lower-case key for grouping |
state, area |
Split from location; numeric areas set to NA |
property_type |
Factor; rare types merged into “Others” |
furnished |
Ordered factor: Not / Partially / Fully Furnished |
monthly_rent_rm |
Monthly rent in RM (numeric) |
size_sqft |
Built-up size in sq.ft. (numeric) |
rent_per_sqft |
monthly_rent_rm / size_sqft |
rooms, bathroom, parking |
Integer counts; implausible values set to NA |
parking_missing |
TRUE if the original parking value was missing |
completion_year |
Integer year; many NA |
flag_rent_psf_outlier |
TRUE if rent per sq.ft. is outside the configured band |
fac_* |
0/1 indicators for building facilities |
add_* |
0/1 indicators for in-unit / nearby features |
n_facilities, n_additional |
Counts of the above |