The data frames used are as follows:
name year price
Company A 1999 200
Company A 2000 202
Company A 2001 199
Company A 2002 400
Company A 2003 207
Company B 1999 300
Company B 2000 500
Company B 2001 201
[1] 199 200 201 202 207
means .
I want to leave only the line where the value of the variable price in the above data frames matches the element of the vector.
The goals are as follows:
name year price
Company A 1999 200
Company A 2000 202
Company A 2001 199
Company A 2003 207
Company B 2001 201
Base R
df<-data.frame(
"name" = c(rep("Company A", 5), rep("Company B", 3)),
"year" = c (1999:2003, 1999:2001),
"price" = c (200, 202, 199, 400, 207, 300, 500, 201)
)
select_price<-c(199,200,201,202,207)
matched <-df [df$price%in%select_price,]
print(matched)
#
name year price
1 Company A 1999 200
2 Company A 2000 202
3A Company 2001 199
5 Company A 2003 207
8B Company 2001 201
dplyr
library(dplyr)
matched<-df%>%filter(price%in%select_price)
print(matched)
#
name year price
1 Company A 1999 200
2 Company A 2000 202
3A Company 2001 199
4 Company A 2003 207
5B Company 2001 201
< For dplyr
, the index is reset.
© 2024 OneMinuteCode. All rights reserved.