我是R的新人,我正在尝试做一些非常简单的事情.我加载了一个包含四列的txt文件,现在我想得到第二列的最小值.这是我的代码:
## 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)
Run Code Online (Sandbox Code Playgroud)
实际上,如果我想做这样的事情:min(data(:,2)).但我不知道如何在R中做到这一点.任何帮助?
Did*_*rts 42
如果您需要特定列的最小值
min(data[,2])
Run Code Online (Sandbox Code Playgroud)
注意:R同时考虑NA
最小值和最大值,因此如果您的列中有NA,则返回:NA
.要补救,请使用:
min(data[,2], na.rm=T)
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
首先,您仅在“Y”列上使用 min 函数找到 Y min。注意返回的结果只是一个整数值。然后,要找到关联的 X 值,您可以将 data.frame 子集到仅最小 Y 值所在的行,并仅提取“X”列。
您现在有 X 和 Y 的两个整数值,其中 Y 是最小值。