Good morning everyone
My problem is very simple: I have numeric vector (example) and from this through if else loop I would like to extract specific values.
example
[1] 0.80 0.58 0.30 0.60 0.30 0.05 1.00 2.00 30.00 1.50
And this is my function which, however, always gives me the same mistake
extractShips = function(i){
ShippingCost = as.numeric()
if(i <= 3){
ShippingCost = 4.40
}else if(i > 3 && i <= 5) {
ShippingCost = 5.90
}else if(i > 5 && i <= 10) {
ShippingCost = 7.80
}else if(i > 10 && i <= 25) {
ShippingCost = 10.90
}else if(i > 25 && i <= 50) {
ShippingCost = 15.90
}else if(i > 50 && i <= 100) {
ShippingCost = 26.00
}
}
**Error in if (y< 0) { : missing value where TRUE/FALSE needed**
ships <- NULL
for (i in 1:nrow(example)) {ships <-c(ships, extractShips(example))
}
thanks in advance to anyone who wants to help me
Descrizione.gruppo Famiglia
1 2 3 0 0 80 ADJ 00BO "BORSE ZAINI CUSTODIE" UA "BORSE" BNO
2 19 29 0 0 830 ADJ 00BO "BORSE ZAINI CUSTODIE" UA "BORSE" BNO
3 0 0 0 0 1 CG MOBILE 00BO "BORSE ZAINI CUSTODIE" UA "BORSE" BNO
4 0 1 0 0 1 KOOPER 00BO "BORSE ZAINI CUSTODIE" UA "BORSE" MY1
5 0 1 0 0 3 LENOVO 00BO "BORSE ZAINI CUSTODIE" UA "BORSE" BNO
6 0 0 0 0 1 RIVACASE 00BO "BORSE ZAINI CUSTODIE" UA "BORSE" BNO
Descrizione.famiglia Peso Volume EAN End.user
1 "BORSA NOTEBOOK" "0.8" "0.004" "8054608902756" 17.89
2 "BORSA NOTEBOOK" "0.575" "0.01" "8054608903197" 8.01
3 "BORSA NOTEBOOK" "0.3" "0.004" "3700740423042" 40.25
4 "SPORT/TEMPO LIBERO" "0.6" "0.01" "8029121921928" 30.99
5 "BORSA NOTEBOOK" "0.3" "0.001" "0193638156338" 43.57
6 "BORSA NOTEBOOK" "0.575" "0.009" "4260403573389" 18.2
>
CodePudding user response:
You can use an apply
family function instead of a for loop.
#First get rid of NA's in the data:
focelda_grezzo$Peso[is.na(focelda_grezzo$Peso)] <- 0
# Define function:
extractShips = function(i){
ShippingCost = as.numeric()
if(i <= 3){
ShippingCost = 4.40
}else if(i > 3 && i <= 5) {
ShippingCost = 5.90
}else if(i > 5 && i <= 10) {
ShippingCost = 7.80
}else if(i > 10 && i <= 25) {
ShippingCost = 10.90
}else if(i > 25 && i <= 50) {
ShippingCost = 15.90
}else if(i > 50 && i <= 100) {
ShippingCost = 26.00
}
}
# Create a new column using your function
focelda_grezzo$ShippingCost <- sapply(focelda_grezzo$Peso, extractShips)