Reputation: 41
I have a dataframe with a names column, date arrival (type date) and price( type numeric) like this
names Datearriv price
SUV 2019-01-16 84,35
HOR 2020-02-28 130,45
SUV 2019-01-16 235,12
Actually I have a problem with my R project. I would like to compare the names, if they are the same, I compare the arrival date if it is the same, I compare the price of the stay and the program has to delete the line with the highest price of stay, i.e. the one with the tax.
I wrote this code but it makes mistakes. Here's my code and the dataframe
for(i in 1:96){nom=data[i,2] date = data[i,4] prix = data[i,8] z = i+1 for(j in z:97){ if(data[j,2] == nom){ if(data[j,4] == date){ if(data[j,8]>prix){ data = data[-j,] else{data = data[-i]}}}}}}
Upvotes: 1
Views: 42
Reputation: 2435
This is one possibility:
d <- read.table(text="
names Datearriv price
SUV 2019-01-16 84,35
HOR 2020-02-28 130,45
SUV 2019-01-16 235,12", header=TRUE
)
library(dplyr)
# Note that your variable is not numeric yet
d <- d %>%
mutate( price = as.numeric(gsub(",", ".", price )))
# now can filter
d <- d %>%
group_by(names, Datearriv) %>% # define the groups
add_count(name="N") %>% # check how many observations per group
mutate( max = max(price) ) %>% # check the max price
filter(!(max==price & N>1) ) %>% # we can drop the observation if teh price is max and we have more than one
dplyr::select(names:price) # select relevant columns
d
# A tibble: 2 x 3
# Groups: names, Datearriv [2]
names Datearriv price
<fct> <fct> <dbl>
1 SUV 2019-01-16 84.4
2 HOR 2020-02-28 130.
Upvotes: 2