04 R语言的函数
标签(空格分隔): R语言
注意一个例子:
MyStrings <- c("This", "is", "a", "string.")
if ("This" %in% MyStrings)
{
print("Found!")
}
else
{
Print("Not Found.")
}
1.注意所使用的**%in%**这个符号,可以在R语言中用于查找。
Num <- as.integer(readline(
"Enter a number between 1 and 5: "))
Result <- switch(
Num,
"One",
"2",
"It's Three!",
"Almost There!",
"Done!")
print(Result)
2.这段代码可以注意的函数有readline()函数(可以读取用户输入的内容),它将返回字符串,除非你使用**as.integer()**来转换字符类型。
3.然后,R语言使用 repeat,while 和for 来进行循环。
4.LessThan()函数 用于比较大小,返回一个真值
5.mean(x, trim=0, na.rm=FALSE)函数 可以用来返回均值。
函数解释:
» x: Contains the input vector
» trim: Determines the number of observations to drop from both ends of the sorted vector
» na.rm: Specifies whether to remove the missing values from the input vector
6.median(x, na.rm=FALSE)函数 :用来返回中间值。变量意义可以参照mean()的解释。
7.安装额外的函数包:
例子:
install.packages("modeest")
#这个命令会寻找、下载并安装所指的包
library(modeest)
#这个命令会在默认库中找到所指的包并加载到内存里
MySamples <- c(19, 4, 5, 7, 29, 19, 29, 13, 25, 19, 42)
mlv(MySamples, method = "mfv")
7.使用 barplot()函数 可以绘制一份柱状图。
然后,我们给出基本语法:
barplot( H , xlab , ylab , main , names.arg , col )
» H: Supplies a vector or matrix containing numeric values used in the bar chart
» xlab: Defines a label for the x-axis
» ylab: Defines a label for the y-axis
» main: Specifies a title for the bar chart
» names.arg: Supplies a vector of names that appear under each bar
» col: Contains a list of colors to use to color the bars in the graph