简体   繁体   中英

Rearranging data columns in R

I have an excel file that contains two columns: Car_Model_Year and Cost .

Car_Model_Year     Cost
2018              25000
2010              9000
2005              13000
2002              35000
1995              8000

I want to sort my data as follows:

Car_Model_Year     Cost
1995               8000
2002               35000
2005               13000
2010               9000
2018               25000

So now, the Car_Model_Year are sorted in ascending order. I wrote the following R code, but I don't know how to rearrange the values of the variable Cost accordingly.

my_data <- read.csv2("data.csv")
my_data <- sort(my_data$Car_Model_Year, decreasing = FALSE)

Any help will be very appreciated!

Does the below approach work? To sort by two or more columns, you just add them to the order() - ie order(var1, var2,...)

my_data <- data.frame(Car_Model_Year=c(2018,2010,2005,2002,1995),
                      Cost=c(25000,9000,13000,35000,8000))

sorted <- my_data[order(my_data$Car_Model_Year, my_data$Cost),]

> print(sorted)
  Car_Model_Year  Cost
5           1995  8000
4           2002 35000
3           2005 13000
2           2010  9000
1           2018 25000

Are you looking for this?

sorted_df <- df[order(df$Car_Model_Year, df$Cost),]
print(sorted_df)

# A tibble: 5 x 2

  Car_Model_Year  Cost
           <dbl> <dbl>
1           1995  8000
2           2002 35000
3           2005 13000
4           2010  9000
5           2018 25000

Note that you can use signs ( + / - ) to indicate asc or desc :

# Sort by car_model(descending) and cost(acending)
sorted_df <-df[order(-df$Car_Model_Year, df$Cost),]

dplyr::arrange() makes it easy:

library(dplyr)
my_data %>% arrange(Car_Model_Year, Cost)

Descending price instead:

my_data %>% arrange(Car_Model_Year, desc(Cost))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM