Reputation: 3938
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?
Upvotes: 30
Views: 188630
Reputation: 453
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.
Upvotes: 7
Reputation: 98449
If you need minimal value for particular column
min(data[,2])
Note: R considers NA
both the minimum and maximum value so if you have NA's in your column, they return: NA
. To remedy, use:
min(data[,2], na.rm=T)
Upvotes: 51
Reputation: 11
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]))
Upvotes: 0
Reputation: 131
If you prefer using column names, you could do something like this as an alternative:
min(data$column_name)
Upvotes: 13