Reputation: 667
I have a table temp1 that has 2 columns "Hospital.Name" and "heart attack" and 1 variable called "colname"
colname <- "heart attack"
Hospital.Name heart attack
ROUND ROCK MEDICAL CENTER 14.9
CYPRESS FAIRBANKS MEDICAL CENTER 12.0
I am trying to bring the record with the lowest "heart attack" number but I am getting an error on my formula it brings nothing, this is what I have:
temp1[which(temp1[[colname1]] == min(as.numeric(temp1[[colname1]]))),]
[1] Hospital.Name heart attack
<0 rows> (or 0-length row.names)
is bringing no results
but I know the right part of the formula is right because when I use
min(as.numeric(temp1[[colname1]]))
[1] 12
I get the min result of the "heart attack" column
Please help me with my formula:
temp1[which(temp1[[colname1]] == min(as.numeric(temp1[[colname1]]))),]
Upvotes: 1
Views: 54
Reputation: 11128
If I understood you correctly then you want all the information against a row for which one of the variables has minimum value.
You can try which.min
if this is what you want to do.
using mtcars data set present in R session:
mtcars[which.min(mtcars$mpg),]
Above will fetch record(row) which has minimum value of mpg field in mtcars data.
#> mtcars[which.min(mtcars$mpg),]
# mpg cyl disp hp drat wt qsec vs am gear carb
#Cadillac Fleetwood 10.4 8 472 205 2.93 5.25 17.98 0 0 3 4
Now If you use which
the way you have used in your dataset, you can have something like this:
mtcars[which(mtcars[[colname1]] == min(mtcars[[colname1]])),]
This will produce two records like below:
#> mtcars[which(mtcars[[colname1]] == min(mtcars[[colname1]])),]
# mpg cyl disp hp drat wt qsec vs am gear carb
#Cadillac Fleetwood 10.4 8 472 205 2.93 5.250 17.98 0 0 3 4
#Lincoln Continental 10.4 8 460 215 3.00 5.424 17.82 0 0 3 4
Moral of the story which.min
produces first instances of logical match, but which
can give you both the instances of the match if there are multiple records of same minimum value.
From Documentation:
Determines the location, i.e., index of the (first) minimum or maximum of a numeric (or logical) vector.
In your case it might be something like:
temp1[which.min(temp1[,colname]) ,]
In case if its not in numeric, then rather doing lot of things in a step, break it for simplicity.
temp1[,colname] <- as.numeric(temp1[,colname]) ##numeric conversion
temp1[which.min(temp1[,colname]) ,]
where colname = "heart attack" as per your question
If you use below code you can have multiple records, also it seems you have written the right code , your code is not working because you have a typo between colname and colname1
temp1[which(temp1[[colname]] == min(temp1[[colname]])),]
Upvotes: 1