-1

I'm trying to convert a column of my data frame (df) into rows. First I imported my dataset from a .xlsx file and made it into a tibble, which originally had 18 rows and 126 columns. The 1st column is a chr data type while the remaining 125 are dbl data type. I then mutated this data to convert the 1st column (col_1) from a chr to a fct data type. And I also selected only 1 other column (col_2), which used to be called 2010-01, and multiplied it by 100 in order to convert it to whole numbers; it still however is a dbl data type. I am now left with 2 columns and 18 rows in my df.

if (!require("pacman")) install.packages("pacman")
pacman::p_load(magrittr, pacman, rio, tidyverse)


# Import data into tibble "df"
df <- import(".xlsx file") %>%
  as_tibble() %>%
  print()

# Define "col_1" as factor
df %<>% 
  mutate(col_1 = as.factor(col_1)) %>%
  print()

# Select col_2, convert to whole numbers
df %<>% 
  mutate(col_2 = `2010-01` * 100) %>%
  select(col_1, col_2) %>%
  print()

# Convert to rows
df %<>% 
  uncount(col_2) %>%
  print()

The problem now is that I'm receiving this error:

Error in `uncount()`: ! Can't convert from `weights` <double> to <integer> due to loss of precision. • Locations: 11

I'm not sure how to fix this. Please help

Kam
  • 1
  • 2
  • 4
    Welcome to SO, Kam! Questions on SO (especially in R) do much better if they are reproducible and self-contained. By that I mean including attempted code (you have this, though `install.packages` should not be in the question unless it fails), sample representative data (perhaps via `dput(head(x))` or building data programmatically (e.g., `data.frame(...)`), possibly stochastically), perhaps actual output (with verbatim errors/warnings) versus intended output. Refs: https://stackoverflow.com/q/5963269, [mcve], and https://stackoverflow.com/tags/r/info. – r2evans Aug 14 '23 at 17:29
  • 1
    ```mutate(col_2 = as.integer(round(`2010-01` * 100, 0)))```? – M-- Aug 14 '23 at 17:45

0 Answers0