Функция с 2 входами корректно работает сама по себе и при зацикливании строк, но при использовании mutate обнаруживается, что она не нужна.
«### Цикл, который дает правильные ответы» - вот что мне нравится.
«### Где появляются сообщения об ошибках» - это то, что не работает. Первая строка eff1 верна, но остальные строки были округлены с использованием значения s из первой строки.
Почему мутация не работает, пожалуйста?
install.packages("reprex")
library(reprex)
library(tidyverse)
### Digit extraction
extract_digit <- function(x, n) {
floor(x / 10^(ceiling(log10(x)) - n )) -
floor(x / 10^(ceiling(log10(x)) - n + 1)) * 10
}
### Round 2 numbers "effectively"
effective_digits1 <- function(x, y)
{
output <- vector("double", 1)
n <- floor(log10(x) + 1)
for(i in 1:n)
{
a.i <- extract_digit(x, i)
b.i <- extract_digit(y, i)
if (a.i - b.i != 0)
{
break
}
}
s = i + 1
output <- signif(x, s)
return(output)
}
### Function works correctly
effective_digits1(6114, 1842)
### Dataframe on which to mutate
motor_vehicles <- data.frame("type_of_vehicle" =
c("Private cars and private vans",
"Motorcycles, scooters and mopeds",
"Public transport vehicles",
"Goods",
"Agricultural tractors etc",
"Other vehicles"),
"y1961" = c(6114, 1842, 94, 1490, 481, 206),
"y1966" = c(9747, 1430, 96, 1611, 478, 260))
### Second df on which to mutate
motor_vehicles2 <- motor_vehicles
### Loop which gives correct answers
for (i in 1:nrow(motor_vehicles)){
motor_vehicles$eff_1961[i] <- effective_digits1(motor_vehicles$y1961[i], motor_vehicles$y1966[i])
}
### Where error messages appear
eff1 <-
motor_vehicles2 %>%
mutate(eff_1961 = effective_digits1(y1961, y1966))
### Loop which gives correct answers - what I'm after
### Where error messages appear -
Warning messages:
1: In 1:n : numerical expression has 6 elements: only the first used
2: In if (a.i - b.i != 0) { :
the condition has length > 1 and only the first element will be used