[r] How to find the minimum value of a column in R?

I am new in R and I am trying to do something really simple. I had load a txt file with four columns and now I want to get the minimum value of the second column. This is the code that I have:

 ## Choose the directory of the file

 setwd("//Users//dkar//Desktop")

 ## Read the txt file

 data<-read.table("export_v2.txt",sep="",header=T)

 str(data)

 ##  this command gives me the minimum for all 4 columns!!
 a<-apply(data,2,min)

Actually, if I want to do something like this: min (data(:,2)). But I don't know how to do it in R. Any help?

This question is related to r

The answer is


If you prefer using column names, you could do something like this as an alternative:

min(data$column_name)

Since it is a numeric operation, we should be converting it to numeric form first. This operation cannot take place if the data is in factor data type.
Check the data type of the columns using str().

min(as.numeric(data[,2]))

df <- read.table(text = 
             "X  Y
             1  2  3
             2  4  5
             3  6  7
             4  8  9
             5 10 11",
             header = TRUE)


y_min <- min(df[,"Y"])

# Corresponding X value
x_val_associated <- df[df$Y == y_min, "X"]

x_val_associated

First, you find the Y min using the min function on the "Y" column only. Notice the returned result is just an integer value. Then, to find the associated X value, you can subset the data.frame to only the rows where the minimum Y value is located and extract just the "X" column.

You now have two integer values for X and Y where Y is the min.