R: minimum and maximum numeric value with name

NAME                                        Number
cars                                         10
people                                       340
bus                                          4

      

I need to find a way to specify the minimum and maximum numerical value with his correspondent name from the first coulmn.

if i put the command:

min(data[,2]) 
max(data[,2]) 

      

only the values ​​are the result

the end result should display like this:

  • for minimum value *

    Bus 4

  • for maximum value *

    people 340

+3


source to share


1 answer


You can get strings min

and max

separately with

df1[which.max(df1[,2]),]

      

or

df1[which.min(df1[,2]),]

      

For plotting the graph can be



df2 <- subset(df1, Number %in% c(min(Number), max(Number)))
m1 <- t(df2[,2])
colnames(m1) <- df2[,1]
barplot(m1)

      

Update

Using the example in the image,

dfN <- data.frame(Col1=c('Controlli di Polizia Giudiziaria', 
'Ricrosi a seguito di contravvenzioni', 
'Ordinanze e inguinzioni sul commercio', 'Automezzi', 
'Chilometri percorsi', 'Infrazioni al codice della strada'),
 number = c(249, 349, 152, 8, 41658 , 8597))

 colnames(m1) <- sub('(\\S+\\s\\S+)\\s(\\S+\\s\\S+)(.*)', 
             '\\1\n\\2\n\\3', dfN[,1])
 barplot(m1, cex.names=0.7)

      

+1


source







All Articles