Albert Roberts
Albert Roberts

Reputation: 23

R - How to change values with decimals into a different form

I have a variable that takes values of the form x.1, x.2 or x.3 currently with x being any number followed by the decimal point.

I would like to convert x.1 to x.333, x.2 to x.666 and x.3 to x.999 or in this case I would assume it would be rounded up to the whole number.

Context: running regression analysis containing a variable of innings pitched (baseball pitchers) which currently have data values of the .1, .2, .3 form above.

Help would be much appreciated!

Upvotes: 2

Views: 428

Answers (2)

JasonAizkalns
JasonAizkalns

Reputation: 20483

Depending on the exact context, it could be nice to keep the component parts -- if that's the case, I would be a little verbose and utilize tidyr and dplyr:

library(tidyr)
library(dplyr)

vec <- c("123.1", "456.2", "789.3")

df <- data.frame(vec)

df %>%
  separate(vec, into = c("before_dot", "after_dot"), remove = FALSE, convert = TRUE) %>%
  mutate(after_dot_times_333 = after_dot * 333,
         new_var = paste(before_dot, after_dot_times_333, sep = "."))

#     vec before_dot after_dot after_dot_times_333 new_var
# 1 123.1        123         1                 333 123.333
# 2 456.2        456         2                 666 456.666
# 3 789.3        789         3                 999 789.999

Alternatively, you could accomplish this in one line:

sapply(strsplit(vec, "\\."), function(x) paste(x[1], as.numeric(x[2]) * 333, sep = "."))

Upvotes: 1

Bill the Lizard
Bill the Lizard

Reputation: 406095

You can use x %% 1 to get the fractional part of a number in R. Then just multiply that by 3.333 and add the result back on to the integer part of your number to get total innings pitched.

x <- 2.3
as.integer(x) + (x %% 1 * 3.333)
[1] 2.9999

(Use 3.333 instead of 0.333 to move the decimal.)

Upvotes: 3

Related Questions