我需要在R中对数据框中的非数值和数值进行排序的帮助。我有一个包含195行和列的数据框,名称如下:
Country.name, Country.code, Birth.rate, Internet.users, and Income.Group
我的任务是创建一个新的数据框,由原始数据框的前30行组成,按收入组按升序排序,然后由互联网用户按降序排序。
收入组有以下几个类别:
high income、upper middle income、lower middle income和low income
Internet.users是数值的。
请帮帮我!
发布于 2018-03-09 01:21:39
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 1197https://stackoverflow.com/questions/49177093
复制相似问题