Вы можете использовать tidyverse
mutate_all
для задания диапазонов:
library(tidyverse)
df<-structure(
list(
x = 1:5,
y = c(1L, 2L, 2L, 2L, 3L),
z = c(1L,3L, 3L, 3L, 2L),
a = c(1L, 5L, 6L, 4L, 8L),
b = c(1L, 3L, 4L, 7L, 1L)
),
class = "data.frame",
row.names = c(NA, -5L)
)
df %>% mutate_all(
funs(
case_when(
. <= 2 ~ 'Bad',
(. > 3) & (. <= 4) ~ 'Good',
(. > 4) ~ 'Excellent',
TRUE ~ as.character(.)
)
)
)
Приведенное выше .
представляет оцениваемый элемент.Это приводит к
x y z a b
1 Bad Bad Bad Bad Bad
2 Bad Bad 3 Excellent 3
3 3 Bad 3 Excellent Good
4 Good Bad 3 Good Excellent
5 Excellent 3 Bad Excellent Bad
Для изменения только выбранных столбцов используйте mutate_at
:
df %>% mutate_at(
vars(
c('a', 'x', 'b')
),
funs(
case_when(
. <= 2 ~ 'Bad',
(. > 3) & (. <= 4) ~ 'Good',
(. > 4) ~ 'Excellent',
TRUE ~ as.character(.)
)
)
)
Это дает
x y z a b
1 Bad 1 1 Bad Bad
2 Bad 2 3 Excellent 3
3 3 2 3 Excellent Good
4 Good 2 3 Good Excellent
5 Excellent 3 2 Excellent Bad
Вот как вы можетезагрузить и классифицировать исходные данные напрямую, используя tidyverse
:
df <- read_csv(
'https://archive.ics.uci.edu/ml/machine-learning-databases/00485/google_review_ratings.csv'
) %>% select(
-X26 # Last column is blank (faulty CSV)
) %>% select_at(
vars(
paste('Category', 1:10) # Pick only Category 1-Category 10
)
) %>% mutate_all(
funs(
case_when(
. <= 2 ~ 'Bad',
(. > 3) & (. <= 4) ~ 'Good',
(. > 4) ~ 'Excellent',
TRUE ~ as.character(.)
)
)
)