具有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