Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 根据其他列的10个最高数字选择10个名称_R_Dplyr - Fatal编程技术网

R 根据其他列的10个最高数字选择10个名称

R 根据其他列的10个最高数字选择10个名称,r,dplyr,R,Dplyr,我想选择前10名的投票餐厅,并将它们放在一起。 所以我想创建一个显示餐厅名称和投票的情节。 我用过: 然后是一个条形图,显示这些餐厅的名称和他们的投票我没有看到要使用的数据集,所以这里有一个简单的例子来说明它是如何工作的: library(tidyverse) df <- tibble( restaurant = c("res1", "res2", "res3", "res4"), votes = c(2, 5, 8, 6) ) df %>% a

我想选择前10名的投票餐厅,并将它们放在一起。 所以我想创建一个显示餐厅名称和投票的情节。 我用过:


然后是一个条形图,显示这些餐厅的名称和他们的投票

我没有看到要使用的数据集,所以这里有一个简单的例子来说明它是如何工作的:

library(tidyverse) 

df <- 
  tibble(
    restaurant = c("res1", "res2", "res3", "res4"),
    votes = c(2, 5, 8, 6)
  )

df %>% 
  arrange(-votes) %>% 
  head(3) %>% 
  ggplot(aes(x = reorder(restaurant, votes), y = votes)) +
  geom_col() +
  coord_flip()
库(tidyverse)
df%
安排(-投票数)%>%
总分(3)%>%
ggplot(aes(x=重新订购(餐厅,投票),y=投票))+
geom_col()+
coord_flip()

在这种情况下,
top\n
命令也可以工作,但它是为分组数据而设计的。

使用基本函数效率更高,但可读性较差:

#toy data
d <- data.frame(list(Names = sample(LETTERS, size = 15), value = rnorm(25, 10, n = 15)))
head(d)
  Names     value
1     D 25.592749
2     B 28.362303
3     H  1.576343
4     L 28.718517
5     S 27.648078
6     Y 29.364797
#reorder by, and retain, the top 10
newdata <- data.frame()
for (i in 1:10) {
      newdata <- rbind(newdata,d[which(d$value == sort(d$value, decreasing = T)[1:10][i]),])
}
newdata
   Names    value
8      W 45.11330
13     K 36.50623
14     P 31.33122
15     T 30.28397
6      Y 29.36480
7      Q 29.29337
4      L 28.71852
10     Z 28.62501
2      B 28.36230
5      S 27.64808
barplot(sort(xtabs(Votes ~ Names, df), decreasing = TRUE)[1:10], xlab = "Restaurant Names")
玩具数据
d另一种简单的方法,用基函数创建另一个变量:

df <- data.frame(Names = LETTERS, Votes = sample(40:400, length(LETTERS)))
x <- df$Votes
names(x) <- df$Names # x <- setNames(df$Votes, df$Names) is another approach
barplot(sort(x, decreasing = TRUE)[1:10], xlab = "Restaurant Name", ylab = "Votes")

尝试使用
%%>%select(yourcolumnnames)
不清楚该问题。请展示一个小的可复制示例/预期输出
top\n(餐厅,10票)
works。
餐厅%>%排名靠前(10票)
。你的代码出了什么问题?我得到了一个不适用于“filter”类对象的“filter”方法
df <- data.frame(Names = LETTERS, Votes = sample(40:400, length(LETTERS)))
x <- df$Votes
names(x) <- df$Names # x <- setNames(df$Votes, df$Names) is another approach
barplot(sort(x, decreasing = TRUE)[1:10], xlab = "Restaurant Name", ylab = "Votes")
barplot(sort(xtabs(Votes ~ Names, df), decreasing = TRUE)[1:10], xlab = "Restaurant Names")