working through an assignment problem, very tired brain right now, could someone nudge me in the right direction please?
I have sorted a dataframe and I have organised what I want - the value of the country with the highest kidnapping rate. I have just learned that I could have used tail instead of head.
TopKidnap <- NoNACountry[order(NoNACountry$Kidnapping, decreasing = TRUE),]
view(TopKidnap)
head(TopKidnap$Kidnapping, 1)
I get the right answer
[1] 7.17
but because I sorted the dataframe, the country name is now row 1.
My goal is to output the row name Luxembourg as well as the value 17. I think I am close with the following code but I'm just not seeing it in the books (R in Action, R Cookbook or R for Data Science). Combing the books with Stack Overflow got here...
head(row.names.data.frame(TopKidnap$Kidnapping), 1)
Could someone nudge me in the right direction please? I constructed the dataframe with the first column as characters that are the country names with the rest of the table as numeric. I think it should be something like addrownums
but I'm not seeing it.
dput below
TopKidnap <- structure(list(Intentional.homicide = c(0.65, 0.71, 1.31, 0.71,
1.28), Attempted.intentional.homicide = c(9.61, 2.18, 1.86, 0.55,
6.46), Assault = c(103.76, 160.31, 1.46, 102.18, 15.31), Kidnapping = c(7.17,
5.44, 2.01, 1.71, 1.17), Sexual.violence = c(48.22, 49.05, 9.85,
67.86, 8.52), Robbery = c(74.44, 43.43, 17.85, 41.66, 11.42),
Unlawful.acts.involving.controlled.drugs.or.precursors = c(690.35,
433.33, 35.72, 421.84, 82.59), Country.Totals.per.000s = c(934.2,
694.45, 70.06, 636.51, 126.75)), row.names = c("Luxembourg",
"Germany (until 1990 former territory of the FRG)", "Romania",
"Ireland", "Kosovo (under United Nations Security Council Resolution 1244/99)"
), class = "data.frame")
One possible way is to subset the data.frame rather than the column. You can do that with
head(TopKidnap[, "Kidnapping", drop=FALSE], 1)
# Kidnapping
# Luxembourg 7.17
The drop=FALSE
is to keep R from simplifying the result. Normally when you select one column it's converted to a vector. drop=FALSE
keeps it as a data.frame which keeps the row names.