I am working on the below data frame where i am trying to multiply the variable x1 with 1.1, x2 with 1.2 and x3 with 1.3 , but i get the below error
Can't convert from double to integer due to loss of precision
Could you please let me know the reason for this and a solution. If i use the integer values (1, 2, 3) then i dont get that error, but i have to use double values to multiply
test <- data.frame(x1=c(1,2,3,4,5,6),
x2=c(2,3,4,5,6,7),
x3=c(3,4,5,6,7,8))
test2 <- test %>% mutate(across(c(x1,x2,x3),.names='y_{.col}')*across(c(1.1,1.2,1.3)))
CodePudding user response:
You can get what you want using the base package with the following code
# Initial test data.frame
test <- data.frame(x1=c(1,2,3,4,5,6),
x2=c(2,3,4,5,6,7),
x3=c(3,4,5,6,7,8))
# Agregate new columns
test <- cbind(test, y1 = test[,1]*1.1,
y2 = test[,2]*1.2,
y3 = test[,3]*1.3)
CodePudding user response:
Using mapply
.
cbind(test, mapply(`*`, test, y))
More specific:
cbind(test, `colnames<-`(mapply(`*`, test, y), paste0('y', seq_along(y))))
# x1 x2 x3 y1 y2 y3
# 1 1 2 3 1.1 2.4 3.9
# 2 2 3 4 2.2 3.6 5.2
# 3 3 4 5 3.3 4.8 6.5
# 4 4 5 6 4.4 6.0 7.8
# 5 5 6 7 5.5 7.2 9.1
# 6 6 7 8 6.6 8.4 10.4
Data:
test <- structure(list(x1 = c(1, 2, 3, 4, 5, 6), x2 = c(2, 3, 4, 5, 6,
7), x3 = c(3, 4, 5, 6, 7, 8)), class = "data.frame", row.names = c(NA,
-6L))
y <- c(1.1, 1.2, 1.3)