#1
x=round(exp(2)/3+abs(tan(-pi/3)),3)
x
## [1] 4.195
typeof(x)
## [1] "double"
#2
x=floor(log(x=sin(pi/3),base = 2))
x
## [1] -1
typeof(x)
## [1] "double"
#3
x=ceiling(cos(pi/4)*sqrt(5)+log(23,base=4))
x
## [1] 4
as.character(x)
## [1] "4"
#4
all.equal(sqrt(3),tan(pi/3))
## [1] TRUE
#5
x=1:100
x[x%%2==0 & x%%3==0]
## [1] 6 12 18 24 30 36 42 48 54 60 66 72 78 84 90 96
x定义如下:x按照“,”或者“;”拆分,并将结果转化成数值型变量。#1
is.numeric(1)
## [1] TRUE
is.character("1")
## [1] TRUE
is.character("one")
## [1] TRUE
”1”, “one”是字符型,1是数值型.
#2
as.numeric(1)
## [1] 1
as.numeric("1")
## [1] 1
as.numeric("one")
## Warning: 强制改变过程中产生了NA
## [1] NA
对“one”进行转换会出错,原因是在R语言中,低等级对象不能转换为高等级,而数值型相对字符型是高等级对象。
#3
#substr('JAN07', 4, 5)+2000
as.numeric(substr('JAN07', 4, 5))+2000
## [1] 2007
substr(‘JAN07’, 4, 5)结果对象为字符型,不能直接与数值型的2000进行数学运算。
#4
x <- '1, 3; 5'
strsplit(x,split =",|;")
## [[1]]
## [1] "1" " 3" " 5"
as.numeric(strsplit(x,split =",|;")[[1]])
## [1] 1 3 5
as.numeric(unlist(strsplit(x,split =",|;")))
## [1] 1 3 5
定义出生日期变量date_bir和发病日期变量date_dis如下:
date_bir <- "1941/3/8"
date_dis <- "2007年1月1日"
Date 和POSIXct日期型。sink()函数将发病年龄保存在test.txt文件中。date_dis中发病年月转换成monyy格式,这里mon是指如SEP的英文三字母缩写, yy是两数字的年份。setwd("D:\\研二上\\实用统计软件\\HWanswer")
#1
as.Date(date_bir)
## [1] "1941-03-08"
as.POSIXct(date_bir)
## [1] "1941-03-08 JST"
as.Date(date_dis,format = "%Y年%m月%d日")
## [1] "2007-01-01"
as.POSIXct(date_dis,format = "%Y年%m月%d日")
## [1] "2007-01-01 CST"
#2
1900+as.POSIXlt(date_bir)$year
## [1] 1941
as.POSIXlt(date_bir)$mon+1
## [1] 3
#3
BurnDay=as.POSIXlt(date_bir)
BeillDay=as.POSIXlt(date_dis,format = "%Y年%m月%d日")
if(BeillDay$mon>BurnDay$mon |(BeillDay$mon=BurnDay$mon & BeillDay$mday>=BurnDay$mday)){
age=BeillDay$year-BurnDay$year
}else{
age=BeillDay$year-BurnDay$year-1
}
sink("text.txt");age;sink()
#4
old.lctime=Sys.getlocale("LC_TIME")
Sys.setlocale("LC_TIME","C")
## [1] "C"
as.character(BeillDay, format='%b%y')
## [1] "Jan07"
x<- factor(c("男", "女", "男"))
x有几个水平值,分别是什么?#1
levels(x)
## [1] "男" "女"
#2
x <- as.ordered(x)
x
## [1] 男 女 男
## Levels: 男 < 女
对levels按照拼音字母表进行排序,将无序的因子型变量,变为有序的因子型变量。
levels()函数把x中的“男”改成“Male”,“女”改成“Female”,并将x通过cat()函数输出到factor.txt文档中。#3
levels(x)=c("male","female")
x
## [1] male female male
## Levels: male < female
cat(x)
## 1 2 1
cat(as.character(x),file = "factor.txt")