在R中的数据帧中对非数值和数值进行排序

时间:2018-03-08 15:45:30

标签: r sorting dataframe lexicographic-ordering

我需要帮助在R的数据框中对非数值和数值进行排序。 我有一个包含195行和列的数据框,其名称如下:

Country.name, Country.code, Birth.rate, Internet.users, and Income.Group

我的任务是创建一个新的数据框,其中包含按收入组按升序排序的原始行的前30行,然后按降序排列互联网用户。

收入组有以下类别:

high incomeupper middle incomelower middle incomelow income

Internet.users是数字。

请帮忙!

1 个答案:

答案 0 :(得分:0)

set.seed(18)

# create sample dataset
df <- data.frame(Country.name = as.character(paste0("Country", 1:195)),
             Income.Group = sample(c("high income", "upper middle income", 
"lower middle income", "low income"), 195, TRUE),
             Internet.users = round(runif(195, 500, 1500),0))

# only take the first 30 entries
df <- df[1:30,] 

# make Income.Group a factor with appropiate order of levels
df$Income.Group <- factor(df$Income.Group, levels = c("low income", "lower 
middle income", "upper middle income", "high income")) 

# first order on Income.Group in ascending order, than on Internet.users in 
# descending order (by using -rank you reverse the Intern.users column)
df <- df[order(df$Income.Group, -rank(df$Internet.users)),]

# take a look at the first 10 rows
head(df, 10)

Country.name           Income.Group     Internet.users
12    Country12          low income           1487
1      Country1          low income           1420
19    Country19          low income           1259
3      Country3          low income           1248
24    Country24          low income           1037
15    Country15          low income           1014
23    Country23          low income            588
17    Country17 lower middle income           1324
26    Country26 lower middle income           1244
6      Country6 lower middle income           1197