Чтобы преобразовать числовые столбцы в проценты в R, можно использовать несколько методов. Вот некоторые часто используемые подходы:
Метод 1: использование пакета dplyr
library(dplyr)
# Assuming your data frame is called 'df' and the numeric columns are 'col1', 'col2', 'col3'
df <- df %>%
mutate(across(c(col1, col2, col3), ~ . / sum(.), .names = "perc_{.col}"))
Метод 2: использование базы R
# Assuming your data frame is called 'df' and the numeric columns are 'col1', 'col2', 'col3'
total <- colSums(df[, c("col1", "col2", "col3")])
df[, c("col1", "col2", "col3")] <- df[, c("col1", "col2", "col3")] / total * 100
Метод 3. Использование пакета data.table
library(data.table)
# Assuming your data table is called 'dt' and the numeric columns are 'col1', 'col2', 'col3'
dt[, c("col1", "col2", "col3") := lapply(.SD, function(x) x / sum(x) * 100), .SDcols = c("col1", "col2", "col3")]