我正在使用 R 数据框架,其中有代表“年份”和“销售额”的列。我想将这些值显示为整数,不带任何小数位。目前,当我创建表格或打印数据框时,“销售额”值显示小数位(例如 10.00),“年份”值也显示小数部分(例如 2019.00)。
我想知道如何格式化这些列,以便它们显示为没有任何小数位的整数。我尝试过使用 format() 函数,但它似乎不会影响这些特定的列。
这是我当前代码的片段:
# Data
sales <- c(10, 30, 50, 20, 40)
revenue <- c(100.25, 300.50, 500.75, 200.00, 400.50)
profit <- c(10.4, 200.7, 400.5, 100.00, 356.79)
year <- c(2019:2023)
data <- rbind(Year = year, Sales = sales, Revenue = revenue, Profit = profit)
# Create a new table with different rows
Table <- kbl(data,
caption = "Development",
booktabs = TRUE,
linesep = c("\\addlinespace[0.2cm]"),
align = c("l", "r")) %>%
kable_styling(latex_options = c("striped"), font_size = 10, position = "left")
Table
任何有关如何实现“销售”和“年份”列格式的指导将不胜感激。预先感谢您的帮助!
不确定包含的 reprex 描述您的实际数据集格式的程度如何。如果您从 Year / Sales / Revenue / Profit 列开始,您可以首先将所有列格式化为字符串,转置以获取字符矩阵中每年的列,并可选择将其返回到 data.frame (
kbl()
将也可以处理矩阵)。
library(kableExtra)
library(dplyr, warn.conflicts = FALSE)
# Data
sales <- c(10, 30, 50, 20, 40)
revenue <- c(100.25, 300.50, 500.75, 200.00, 400.50)
profit <- c(10.4, 200.7, 400.5, 100.00, 356.79)
year <- c(2019:2023)
# reprex from Q, a numeric matrix:
data_old <- rbind(Year = year, Sales = sales, Revenue = revenue, Profit = profit)
data_old
#> [,1] [,2] [,3] [,4] [,5]
#> Year 2019.00 2020.0 2021.00 2022 2023.00
#> Sales 10.00 30.0 50.00 20 40.00
#> Revenue 100.25 300.5 500.75 200 400.50
#> Profit 10.40 200.7 400.50 100 356.79
str(data_old)
#> num [1:4, 1:5] 2019 10 100.2 10.4 2020 ...
#> - attr(*, "dimnames")=List of 2
#> ..$ : chr [1:4] "Year" "Sales" "Revenue" "Profit"
#> ..$ : NULL
# a more conventional representation of that dataset:
data_new <- data.frame(Year = year, Sales = sales, Revenue = revenue, Profit = profit)
data_new
#> Year Sales Revenue Profit
#> 1 2019 10 100.25 10.40
#> 2 2020 30 300.50 200.70
#> 3 2021 50 500.75 400.50
#> 4 2022 20 200.00 100.00
#> 5 2023 40 400.50 356.79
str(data_new)
#> 'data.frame': 5 obs. of 4 variables:
#> $ Year : int 2019 2020 2021 2022 2023
#> $ Sales : num 10 30 50 20 40
#> $ Revenue: num 100 300 501 200 400
#> $ Profit : num 10.4 200.7 400.5 100 356.8
data_wide <- data_new %>%
mutate(across(everything(), format)) %>%
tibble::column_to_rownames("Year") %>%
t() %>%
as.data.frame()
data_wide
#> 2019 2020 2021 2022 2023
#> Sales 10 30 50 20 40
#> Revenue 100.25 300.50 500.75 200.00 400.50
#> Profit 10.40 200.70 400.50 100.00 356.79
str(data_wide)
#> 'data.frame': 3 obs. of 5 variables:
#> $ 2019: chr "10" "100.25" " 10.40"
#> $ 2020: chr "30" "300.50" "200.70"
#> $ 2021: chr "50" "500.75" "400.50"
#> $ 2022: chr "20" "200.00" "100.00"
#> $ 2023: chr "40" "400.50" "356.79"
kbl(data_wide,
caption = "Development",
booktabs = TRUE,
linesep = c("\\addlinespace[0.2cm]"),
align = c("l", "r")) %>%
kable_styling(latex_options = c("striped"), font_size = 10, position = "left")
创建于 2023-08-31,使用 reprex v2.0.2