【问题标题】:Sorting non numerical and numerical values in a data frame in R在R中的数据框中对非数值和数值进行排序
【发布时间】:2018-03-09 02:29:13
【问题描述】:

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

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

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

收入组有以下几类:

high incomeupper middle incomelower middle incomelow income

Internet.users 是数字。

请帮忙!

【问题讨论】:

标签: r sorting dataframe lexicographic-ordering


【解决方案1】:
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

【讨论】:

    猜你喜欢
    • 2017-08-15
    • 1970-01-01
    • 2021-10-29
    • 1970-01-01
    • 1970-01-01
    • 2018-10-17
    • 2020-08-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多