Sorting out a dataframe in ascending order

I urgently need help on this code. I am not getting the right results as I want my output to be arranged from ascending order of 1 to 10

LX <- data.frame(age = c("10-WNW", "0-N", "4-ESE", "1-NNE", "2-ENE", "3-E", "11-NNW", "4-ESE"), income = c( 25.2, 10.5, 11, 21.9, 44, 11.5, 45, 16))

print(LX)

foo <- LX
foo[order(foo$age), ]

'''

LX <- data.frame(age = c("10-WNW", "0-N", "4-ESE", "1-NNE", "2-ENE", "3-E", "11-NNW", "4-ESE"), income = c( 25.2, 10.5, 11, 21.9, 44, 11.5, 45, 16))

print(LX)

foo <- LX
foo[order(foo$age), ]

"'

Sampled dataset

    age income

1 10-WNW 25.2
2 0-N 10.5
3 4-ESE 11.0
4 1-NNE 21.9
5 2-ENE 44.0
6 3-E 11.5
7 11-NNW 45.0
8 4-ESE 16.0

Generated result

  age income

2 0-N 10.5
1 10-WNW 25.2
7 11-NNW 45.0
4 1-NNE 21.9
5 2-ENE 44.0
6 3-E 11.5
3 4-ESE 11.0
8 4-ESE 16.0

Expected result

  age income

2 0-N 10.5
4 1-NNE 21.9
5 2-ENE 44.0
6 3-E 11.5
3 4-ESE 11.0
8 4-ESE 16.0
1 10-WNW 25.2
7 11-NNW 45.0

This is happening because the variable you are using to order your data is a character variable and not a numeric variable, so all values starting with 1 come before those starting with 2.

One approach would be to split age into two variables and convert age into a numeric variable. Then, you can sort by that column and get your expected results.

library(tidyverse)
LX <- data.frame(
  age = c("10-WNW", "0-N", "4-ESE", "1-NNE", "2-ENE", "3-E", "11-NNW", "4-ESE"),
  income = c( 25.2, 10.5, 11, 21.9, 44, 11.5, 45, 16))

LX %>% 
  separate(age, into = c("age", "direction"), sep = "-") %>% 
  mutate(age = as.numeric(age)) %>% 
  arrange(age)
#>   age direction income
#> 1   0         N   10.5
#> 2   1       NNE   21.9
#> 3   2       ENE   44.0
#> 4   3         E   11.5
#> 5   4       ESE   11.0
#> 6   4       ESE   16.0
#> 7  10       WNW   25.2
#> 8  11       NNW   45.0

Created on 2019-08-06 by the reprex package (v0.3.0)

3 Likes

Yeah, just tested your suggestion with my sampled datasaset. It worked fine (plotting the wind rose using age and income) except that the plot of the wind rose ( direction with income ) doesn't produce the right result after sorting the direction with respect to the income. It sorted the alphabets (N, ESE, W, SSW...) in ascending order (A., B, C,..... Z) and by the time the wind rose is plotted, it makes the first alphabet as its reference point instead of the first letter in the Column.

Wind Rose (age and income)

#> age income
#> 1 0 10.5

Wind Rose (direction and income)

#> direction. income
#> 1 E. 11.5

I will just opt for the plot of the wind rose based on the age and income. Thus, the desired result is obtained with your suggestion.

Thank you so much

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.