R Sprache

先看一下R能干什么

df <- mtcars
?mtcars

names(df)
head(df)
nrow(df)
summary(df)

hist(df$hp)
plot(df$hp,df$qsec)

cor(df$hp,df$qsec)
cor(df$cyl,df$qsec)

df$hpPerCyl <- df$hp/df$cyl

df[order(df$hpPerCyl),]
head(df[order(df$hpPerCyl),])

基础内容

如何给变量赋值

#either
x <- 1
#or
x = 1

注意不要忘了空白号,x<-1会被翻译成x <- 1而不是x < -1

R的基本原子类型(atomic types)

x <- TRUE   #class(x) is "logical"
x <- 1L     #class(x) is "integer"
x <- 1.5    #class(x) is "numeric"
x <- 1.5 + o.4i #class(x) is "complex"
x <- "Text" #class(x) is "character"

R中不含有标量(scalars),标量在这里被表示为长度为1的向量。
TRUE和FALSE可以简单的用T,F来代替
Strings即可以用双括号也可以用单括号阔起来

如何调用函数

ls      #is a function object
ls()    #is the object returned by calling the function

如何寻求帮助

#open help:
?ls

#search help for the specific topic:
??correlation

#other functions to analyze things
str(x)
summary(x)
class(x)
attributes(x)

R的控制流

#if:
if(STATEMENT)
    STATEMENT
else
    STATEMENT

#for loop:
for(name in vector)
    STATEMENT

#repeat
repeat
    STATEMENT #until 'break' is called

有趣的地方是:if结构可以被当成statement使用(只有if结构可以):

y <- if(x > 0) "y" else "no"

另外STATEMENT也可以被用{}包围起来的一组statement代替,这些语句可以全部扔在一行,也可以分成多行写

if({x <- mean(1:5); y <- mean(1:4); x<y}){
cat("evaluating the 'true' block \n")
"y"
}else {
cat("evaluating the 'false' block \n")
"n"
}

向量(Vectors)

如何生成向量

x <- c(1,2,3)   #c for "c"Kombine
x <- seq(1,3)   #to create a sequence, with possibility to
x <- seq(1,3,by=0.5)    #-define step size
x <- seq(1,3,len=10)    #-define numer of steps
x <- 1:3        #quick notation for integer sequences
x <- rep(0,10)  #repeat first "vector" 10 times
x <- numeric(10)#"numeric" vector of length 10
x[1] = 10
x[2] = 20
x[3] = 30

无论如何c()的结果都会被铺平所以试试这个吧:

x <- c(1,c(c(2,3),c(4,5,6)))

另外原子向量中是允许缺值的:

c(T,F,T,NA)
c(1:5,NA)
c("A",NA,"B","C",NA)

如果在一个Vector中混合不同类型的值会怎么样呢

因为vector中的值的类性应该一直保持一致,因此当上述情况发生时,R会强制改变类型。他们的优先顺序是:logical,integer,numeric,complex,character

#notice how the type changes when you remove elements from the end
x <- c(T,1L,1.0,1i,"text")
#notice that modifying elements can change the whole type
x <- rep(F,10)
x[6] = "text"

关于vector的一些重要函数

x <- runif(10)

length(x)
sum(x)

#statistics
mean(x)
median(x)
var(x)
sd(x)
quantile(x)

#range related
min(x)
max(x)
range(x)

#sorting related
sort(x)
rank(x)
order(x)

#vectorized functions
x + 1
x * 10
x < 0.5
(x < 0.2)|(x > 0.8)
sin(x)
exp(x)
round(x)

如果用不同长度的两个vector进行运算会怎么样

c(1,2,3,4) + c(1,2)
c(1,2,3,4) + c(1,2,3)
c(1,2,3,4) > 1

R采用的是循环的机制,但这也就要求长的vector的长度应该是短的vector的长度的整数倍

如何使用索引

x <- 1:10 * 10

#a positive index select an element
#a negative index omits an element
x[3]
x[-3]

#indices can again be vectors
x[c(1,3,5)]
x[3:5]
x[-c(1,3,5)]
x[-(3:5)]
#note:mixing positive and negative indices does not make sense

#indices can also be logical vectors
x[c(T,F,T,F,T,F,F,F,F,F)]
x[x == 10 | x == 30]

#indices can even be named
names(x) <- c("a","b","c","d","e","f","g","h","i","j")
x
x["c"]

矩阵和数组

R的vector其实就是其他语言中的array。他没有纬度的概念,只有长度。
R的array是特指多维的array。他有确定的纬度。但是本质上,他也是由vector实现的
R的matrix就是指一个二维的array

如何构建一个matrix

#generate without a vector
m <- matrix(nrow=2, ncol=3)
m[1,1] = 1
m[2,1] = 2
m[1,2] = 3
m[2,2] = 4
m[1,3] = 5
m[2,3] = 6

#generate from ONE vector
matrix(1:6, nrow=2, ncol=3)
matrix(1:6, nrow=2)
matrix(1:6, ncol=3)
matrix(1:6, byrow=TRUE, ncol=3)

#generate from multiple column/row vectors
rbind(c(1,3,5),c(2,4,6))
cbind(1:2,3:4,5:6)

因为matrix本质上就是一个拥有纬度的vector,因此也可以通过vector来构造matrix

m <- 1:12
dim(m) <- c(2,6)
dim(m) <- c(3,2,2)
c(is.vector(m),is.matrix(m),is.array(m))

matrix又是如何使用索引的呢

和vector一样

m[2,2]
m[1,1:3]
m[1,]
m[,2]

唯一不同的是现在要给元素起名的话,要加上纬度属性了

colnames(m) <- c("A","B","C")
rownames(m) <- c("o1","o2")
dimnames(m)

attibutes(m)

进行简单的线性运算

m <- cbind(1:2,3:4,5:6)

#multiply by vectors
m %*% c(1,2,4)
c(5,6) %*% m

第一个c三行一列,第二个c一行两列。真心不知道他在玩什么。以为他能自动转化吗,于是试了以下用c(1,2,3,4) %% m.结果却是出现错误,我还以为可以自动翻译成两行两列呢??然后又试了以下,5 %% m。结果还是错了

#multiply by matrices
m %*% matrix(runif(6),nrow=3)

#typical unary operators
m <- cbind(1:2,3:4)
t(m)        #transpose
diag(m)     #diagonal
solve(m)    #inverse
eigen(m)    #eigenvector/eigenvalues

#solving linear equations
solve(m,c(1,1)) #solve mx=c(1,1) for x

#misc matrix functions
dim(m)
nrow(m)
ncol(m)
rowSums(m)
colSums(m)
rowMeans(m)
colMeans(m)

其他数据类型

R语言中的list

#to construct a list
l <- list(name="Joe", unemployed=FALSE, salary=50000)

#naming the fields is optional 
l <- list("Joe",FALSE,50000)

#in fact, the mechanism to set the "names" is the same as for vectors
names(l) <- c("name", "unemployed", "salary")

#access single elements
l[[1]]
l$name
l["name]
l$sal #it is even allowed to abbreviate the names if it is unique

#generate a "sub" list
l[c(1,3)]
l[c("name","salary")]
l[1]

#"fields" can be added dynamically
l$department <- "IT"
l[["position"]] <- c("consultant","developer")
#note that this can create gaps and unnamed fields
l[[8]] <- TRUE

好像只有在$后面的才能以省略

R语言中的factor

f <- factor(c("A","B","C","A","B","A","A"), ordered = T)
attributes(f)
levels(f)
summary(f)

#to rename a category
levels(f)[1] <- "a"

#to convert to a numeric type
as.numeric(f)
#or:
attributes(f) <- NULL

R语言的data.frame

#create a data frame manually
df <- data.frame(x=runif(20), y=runif(20), type=as.factor(runif(20) > 0.5))
str(df)

#create a new "feature"
df$z <- df$x * df$y
df

#sort by a feature
permutation <- order(df$x)
df <- df[permutation,]

#remove features
toRemove <- c("x","y")
toRemoveLogical <- names(df) %in% toRemove
df <- df[,!toRemoveLogical]
df <- df[,!toRemoveLogical, drop= FALSE]
#better if only one feature is kept

#there is also the powerful "subset" function
#parameter "subset" works on rows
#parameter "subset" works on columns
subset(df, subset = x > 0.5, select = c(y,z))

什么是S3/S4 classes

不知??

Functions

如何定义一个function

nameOfMyFunction <- function(a,b){
return (a+b)
}

注意,return需要有圆括号,另外如果没有return的话,那就默认返回最后一个statement

如何定义函数的默认参数

myfunc <- function(range = 1 : myelin) range^2
myfunc(1:5)

mylen=10
myfunc()

mylen=5
myfunc()

rm(malen)
myfunc()

如何返回多于一个值

myfunc <- function(){
    list(result=42,additional="no errors",numberOfIterations=4)
}
ret <- myfunc()
ret$result
ret$numberOfIterations

补充

R里是否有预定义的变量

答案是有得如:
mtcars
Nile
iris
diamonds

如何连接两个strings

注意不能直接用“+”连接起来

paste("concatenate", "these", "strings")
paste("concatenate", "these", "strings", seq="")

也可以用paste0(…),他的效率比paste好一点点

如何标准输出

x <- 1:10
cat(sprintf("the sum of %d elements is %f\n", length(x), sum(x)))

如何生成随机数

hist(rnorm(1000))
hist(runif(1000))
hist(rbeta(1000,2,4))
hist(rbinom(1000,3,0.5))

Plotting

#histograms:
hist(rnom(1000))
#scatter plots:
plot(rnom(100), rnorm(100)
#line plots:
x <- seq(0, 2*pi, len=100)
plot(x, sin(x)^2+tan(x), type='l'

Numerical Measures

duration = faithful$eruptions
mean(duration)
median(duration)
quantile(duration)
quantile(duration,c(.37,.45,.99))
var(duration)   #variance

waiting = faithful$waiting
cov(duration,waiting)   #covariance

cor(duration, waiting)  #correlation coefficient
cov(duration, waiting)/(sd(duration)*sd(waiting))#standard deviations

概率分布

//待补

静态测试

//待补

这段maxscript代码中 “物体列表” 这四个字 和 “操作” 这两个字 没有根据选择的语言切换到对应的语言文字,修改代码使其切换到对应的语言文字。 代码:try(destroyDialog rolOrderedSelection)catch() -- ======================== -- 多语言支持系统 -- ======================== struct LanguageStrings ( toolTitle, -- 工具标题 labelLanguage, -- 语言选择标签 groupNameSetting, -- 命名设置组标题 labelPrefix, -- 前缀标签 labelInfix, -- 中缀标签 labelSuffix, -- 后缀标签 groupObjectList, -- 物体列表组标题 listBoxObjects, -- 列表框标题 btnClear, -- 清空按钮文本 btnSelectAll, -- 全选按钮文本 groupOperation, -- 操作组标题 btnRenameObjects, -- 重命名按钮文本 msgEmptyList, -- 空列表消息 titleEmptyList, -- 空列表标题 msgNoNamingPart, -- 无命名部分消息 titleWarning, -- 警告标题 msgRenameSuccess, -- 重命名成功消息 titleComplete, -- 完成标题 msgListEmpty, -- 列表为空消息 -- 语言选项 languages = #("中文", "English", "Deutsch", "Français", "日本語", "한국어"), languageCodes = #("Chinese", "English", "German", "French", "Japanese", "Korean") ) -- 中文翻译 fn ChineseStrings = ( LanguageStrings \ toolTitle:"顺序选择工具" \ labelLanguage:"语言选择" \ groupNameSetting:"命名设置" \ labelPrefix:"前缀:" \ labelInfix:"中缀:" \ labelSuffix:"后缀:" \ groupObjectList:"物体列表" \ listBoxObjects:"已选物体:" \ btnClear:"清空列表" \ btnSelectAll:"全选列表物体" \ groupOperation:"操作" \ btnRenameObjects:"应用命名规则" \ msgEmptyList:"列表为空,没有物体可重命名。" \ titleEmptyList:"提示" \ msgNoNamingPart:"请至少填写一个命名部分(前缀、中缀或后缀)。" \ titleWarning:"警告" \ msgRenameSuccess:"成功重命名 % 个主物体及其子级!" \ titleComplete:"完成" \ msgListEmpty:"列表为空" ) -- 英语翻译 fn EnglishStrings = ( LanguageStrings \ toolTitle:"Ordered Selection Tool" \ labelLanguage:"Language" \ groupNameSetting:"Naming Settings" \ labelPrefix:"Prefix:" \ labelInfix:"Infix:" \ labelSuffix:"Suffix:" \ groupObjectList:"Object List" \ listBoxObjects:"Selected Objects:" \ btnClear:"Clear List" \ btnSelectAll:"Select All Objects" \ groupOperation:"Operation" \ btnRenameObjects:"Apply Naming Rule" \ msgEmptyList:"List is empty, no objects to rename." \ titleEmptyList:"Note" \ msgNoNamingPart:"Please fill at least one naming part (prefix, infix or suffix)." \ titleWarning:"Warning" \ msgRenameSuccess:"Successfully renamed % objects and their children!" \ titleComplete:"Complete" \ msgListEmpty:"List is empty" ) -- 德语翻译 fn GermanStrings = ( LanguageStrings \ toolTitle:"Geordnete Auswahl Werkzeug" \ labelLanguage:"Sprache" \ groupNameSetting:"Namenseinstellungen" \ labelPrefix:"Präfix:" \ labelInfix:"Infix:" \ labelSuffix:"Suffix:" \ groupObjectList:"Objektliste" \ listBoxObjects:"Ausgewählte Objekte:" \ btnClear:"Liste leeren" \ btnSelectAll:"Alle Objekte auswählen" \ groupOperation:"Operation" \ btnRenameObjects:"Namensregel anwenden" \ msgEmptyList:"Liste ist leer, keine Objekte zum Umbenennen." \ titleEmptyList:"Hinweis" \ msgNoNamingPart:"Bitte mindestens einen Namensbestandteil ausfüllen (Präfix, Infix oder Suffix)." \ titleWarning:"Warnung" \ msgRenameSuccess:"% Objekte und ihre Kinder erfolgreich umbenannt!" \ titleComplete:"Abgeschlossen" \ msgListEmpty:"Liste ist leer" ) -- 法语翻译 fn FrenchStrings = ( LanguageStrings \ toolTitle:"Outil de sélection ordonnée" \ labelLanguage:"Langue" \ groupNameSetting:"Paramètres de nommage" \ labelPrefix:"Préfixe:" \ labelInfix:"Infixe:" \ labelSuffix:"Suffixe:" \ groupObjectList:"Liste d'objets" \ listBoxObjects:"Objets sélectionnés:" \ btnClear:"Vider la liste" \ btnSelectAll:"Sélectionner tous les objets" \ groupOperation:"Opération" \ btnRenameObjects:"Appliquer la règle de nommage" \ msgEmptyList:"La liste est vide, aucun objet à renommer." \ titleEmptyList:"Note" \ msgNoNamingPart:"Veuillez remplir au moins une partie du nom (préfixe, infixe ou suffixe)." \ titleWarning:"Avertissement" \ msgRenameSuccess:"% objets principaux et leurs enfants renommés avec succès !" \ titleComplete:"Terminé" \ msgListEmpty:"La liste est vide" ) -- 日语翻译 fn JapaneseStrings = ( LanguageStrings \ toolTitle:"順次選択ツール" \ labelLanguage:"言語選択" \ groupNameSetting:"命名設定" \ labelPrefix:"プレフィックス:" \ labelInfix:"インフィックス:" \ labelSuffix:"サフィックス:" \ groupObjectList:"オブジェクトリスト" \ listBoxObjects:"選択済みオブジェクト:" \ btnClear:"リストをクリア" \ btnSelectAll:"リスト内のオブジェクトを全選択" \ groupOperation:"操作" \ btnRenameObjects:"命名規則を適用" \ msgEmptyList:"リストが空です。名前を変更するオブジェクトがありません。" \ titleEmptyList:"注意" \ msgNoNamingPart:"少なくとも1つの命名部分(プレフィックス、インフィックス、サフィックス)を入力してください。" \ titleWarning:"警告" \ msgRenameSuccess:"% 個のメインオブジェクトとその子オブジェクトの名前変更が成功しました!" \ titleComplete:"完了" \ msgListEmpty:"リストが空です" ) -- 韩语翻译 fn KoreanStrings = ( LanguageStrings \ toolTitle:"순차 선택 도구" \ labelLanguage:"언어 선택" \ groupNameSetting:"이름 설정" \ labelPrefix:"접두사:" \ labelInfix:"중간어:" \ labelSuffix:"접미사:" \ groupObjectList:"객체 목록" \ listBoxObjects:"선택된 객체:" \ btnClear:"목록 지우기" \ btnSelectAll:"목록 객체 모두 선택" \ groupOperation:"작업" \ btnRenameObjects:"명명 규칙 적용" \ msgEmptyList:"목록이 비어 있습니다. 이름을 변경할 객체가 없습니다." \ titleEmptyList:"알림" \ msgNoNamingPart:"적어도 하나의 명명 부분(접두사, 중간어 또는 접미사)을 입력하십시오." \ titleWarning:"경고" \ msgRenameSuccess:"% 개의 메인 객체와 그 하위 객체의 이름이 성공적으로 변경되었습니다!" \ titleComplete:"완료" \ msgListEmpty:"목록이 비어 있습니다" ) -- 获取当前语言字符串 fn getCurrentStrings languageCode = ( case languageCode of ( "Chinese": ChineseStrings() "English": EnglishStrings() "German": GermanStrings() "French": FrenchStrings() "Japanese": JapaneseStrings() "Korean": KoreanStrings() default: ChineseStrings() -- 默认为中文 ) ) -- 全局变量存储当前语言 global g_OrderedSelectionLanguage = "Chinese" -- ======================== -- 主工具界面 -- ======================== rollout rolOrderedSelection "顺序选择工具" width:300 height:440 ( -- 存储选择的物体 local objArray = #() -- 当前语言字符串 local currentStrings = getCurrentStrings g_OrderedSelectionLanguage -- 语言选择 - 使用当前语言的标签 dropdownList ddlLanguage "" items:currentStrings.languages width:280 align:#center -- 命名设置组 group "命名设置" ( label lblPrefix "前缀:" across:2 editText edtPrefix "" width:180 label lblInfix "中缀:" across:2 editText edtInfix "" width:180 label lblSuffix "后缀:" across:2 editText edtSuffix "" width:180 ) -- 物体列表组 group "物体列表" ( label lblObjects "已选物体:" listBox lbxObjects "" height:12 width:280 button btnClear "清空列表" width:280 button btnSelectAll "全选列表物体" width:280 ) -- 操作组 group "操作" ( button btnRenameObjects "应用命名规则" width:280 ) -- ======================== -- 工具功能函数 -- ======================== -- 用分隔符连接字符串数组 fn joinStrings strArray delimiter = ( if strArray.count == 0 do return "" local result = strArray[1] for i = 2 to strArray.count do result += delimiter + strArray[i] result ) -- 更新列表显示 fn updateList = ( local items = #() for i = 1 to objArray.count do ( append items (i as string + ": " + objArray[i].name) ) lbxObjects.items = items ) -- 递归命名函数 fn renameHierarchy obj prefix parentInfix suffix baseIndex:1 = ( if not isValidNode obj do return baseIndex -- 构建当前物体名称 local nameParts = #() local currentInfix = parentInfix if prefix != "" do append nameParts prefix if currentInfix != "" do append nameParts currentInfix if suffix != "" do append nameParts (suffix + (formattedPrint baseIndex format:"03d")) -- 应用新名称 if nameParts.count > 0 do obj.name = joinStrings nameParts "_" -- 处理子级 local counter = baseIndex + 1 for child in obj.children do ( counter = renameHierarchy child prefix currentInfix suffix baseIndex:counter ) return counter ) -- 选择变化时的处理 fn selectionChanged = ( if selection.count == 1 and findItem objArray selection[1] == 0 then ( append objArray selection[1] updateList() ) ) -- 应用命名规则 fn renameObjects = ( if objArray.count == 0 then ( messageBox currentStrings.msgEmptyList title:currentStrings.titleEmptyList return undefined ) local prefix = trimRight (trimLeft edtPrefix.text) local infix = trimRight (trimLeft edtInfix.text) local suffix = trimRight (trimLeft edtSuffix.text) if prefix == "" and infix == "" and suffix == "" then ( messageBox currentStrings.msgNoNamingPart title:currentStrings.titleWarning return undefined ) -- 为每个物体应用命名 for i = 1 to objArray.count do ( local obj = objArray[i] if isValidNode obj then ( local parentInfix = if infix != "" then (infix + (i as string)) else "" renameHierarchy obj prefix parentInfix suffix baseIndex:1 ) ) local successMsg = substituteString currentStrings.msgRenameSuccess "%" (objArray.count as string) messageBox successMsg title:currentStrings.titleComplete updateList() -- 更新列表显示新名称 ) -- 刷新UI文本 fn refreshUI = ( -- 更新窗口标题 rolOrderedSelection.title = currentStrings.toolTitle -- 更新语言选择标签 ddlLanguage.caption = currentStrings.labelLanguage -- 获取所有控件 local allControls = rolOrderedSelection.controls -- 查找并更新组标题 for i = 1 to allControls.count do ( local ctrl = allControls[i] -- 命名设置组 if classof ctrl == RolloutGroupControl and ctrl.caption == "命名设置" then ( ctrl.caption = currentStrings.groupNameSetting ) -- 物体列表组 else if classof ctrl == RolloutGroupControl and ctrl.caption == "物体列表" then ( ctrl.caption = currentStrings.groupObjectList ) -- 操作组 else if classof ctrl == RolloutGroupControl and ctrl.caption == "操作" then ( ctrl.caption = currentStrings.groupOperation ) ) -- 更新标签文本 lblPrefix.caption = currentStrings.labelPrefix lblInfix.caption = currentStrings.labelInfix lblSuffix.caption = currentStrings.labelSuffix lblObjects.caption = currentStrings.listBoxObjects -- 更新按钮文本 btnClear.caption = currentStrings.btnClear btnSelectAll.caption = currentStrings.btnSelectAll btnRenameObjects.caption = currentStrings.btnRenameObjects ) -- 初始化UI fn initUI = ( -- 设置语言下拉框 ddlLanguage.items = currentStrings.languages -- 查找并设置当前语言 local langIndex = findItem currentStrings.languageCodes g_OrderedSelectionLanguage if langIndex == 0 do langIndex = 1 ddlLanguage.selection = langIndex -- 更新所有文本 refreshUI() ) -- ======================== -- 事件处理 -- ======================== -- 窗口打开时 on rolOrderedSelection open do ( -- 添加选择变化回调 callbacks.addScript #selectionSetChanged "rolOrderedSelection.selectionChanged()" id:#orderedSelection -- 初始化UI initUI() ) -- 窗口关闭时 on rolOrderedSelection close do ( -- 移除选择变化回调 callbacks.removeScripts id:#orderedSelection ) -- 语言选择变化 on ddlLanguage selected idx do ( g_OrderedSelectionLanguage = currentStrings.languageCodes[idx] currentStrings = getCurrentStrings g_OrderedSelectionLanguage refreshUI() ) -- 清空列表按钮 on btnClear pressed do ( objArray = #() updateList() ) -- 全选列表物体按钮 on btnSelectAll pressed do ( if objArray.count > 0 then select objArray else messageBox currentStrings.msgListEmpty ) -- 列表双击删除 on lbxObjects doubleClicked idx do ( if idx > 0 and idx <= objArray.count then ( deleteItem objArray idx updateList() ) ) -- 应用命名规则按钮 on btnRenameObjects pressed do ( renameObjects() ) ) -- 创建对话框 createDialog rolOrderedSelection
最新发布
08-07
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值