Economist_Ayahuasca
Economist_Ayahuasca

Reputation: 1642

R: selecting the names of the 2 columns with the highest colSums in r

I have the following dataset:

df = 
A B C D
1 4 0 8
0 6 0 9
0 5 0 6
1 2 0 9

I want to obtain a vector with the names of the two columns with the highest colSum:

"B" "D"

So far I have tried:

List_names_TOP2 <- str(sort(colSums(df), 
                 decreasing = TRUE)[1:2])

but I get an error. Any recommendation?

Upvotes: 1

Views: 94

Answers (1)

akrun
akrun

Reputation: 887881

Use the named vector from colSums ('v1') to order in decreasing and subset the first two names with head and sort those column names

v1 <-  colSums(df)
sort(head(names(v1)[order(-v1)], 2))
#[1] "B" "D"

data

df <- structure(list(A = c(1L, 0L, 0L, 1L), B = c(4L, 6L, 5L, 2L), 
    C = c(0L, 0L, 0L, 0L), D = c(8L, 9L, 6L, 9L)), 
    class = "data.frame", row.names = c(NA, 
-4L))

Upvotes: 2

Related Questions