I have a data frame that has values separated by comma or space. How to round these values?
The data frame looks like this:
test_type test_runs test_values
a 2 0.522,0.433
b 3 1.233,1.455,1.344
I want to round the values, output the column without list, and print out the data frame with fixed number of digits using gridextra.
library(dplyr)
data <- data.frame(test_type = c("a","a","b","b","b"),
test_values = c(0.522,0.433,1.233,1.455,1.344)) %>%
group_by(test_type) %>%
summarise(test_runs=n(), test_values=paste(test_values, collapse=","))
round_data <- round(data, digits=2)
A solution from tidyverse
. dt2
is the final output.
# Create example data frame
dt <- read.table(text = "test_type test_runs test_values
a 2 0.522,0.433
b 3 1.233,1.455,1.344",
header = TRUE, stringsAsFactors = FALSE)
# Load package
library(tidyverse)
# Process the data
dt2 <- dt %>%
mutate(test_values = strsplit(test_values, split = ",")) %>%
mutate(test_values = map(test_values, as.numeric)) %>%
mutate(test_values = map(test_values, formatC, format = "f", digits = 2)) %>%
mutate(test_values = map_chr(test_values, paste, collapse = ","))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.