R实战系列专栏
sprintf各种类型转换为字符串时格式化
下面的例子将整数转换为字符串,不足7位在前面补0
> idx = sprintf("%07d", 732)
> idx
[1] "0000732"
> str(idx)
chr "0000732"
具体可以使用help查看
直接上代码
不同类型之间的转换靠as.的成员函数。用RStudio即可看到代码补全
> x<-c(1,12,4)
> x
[1] 1 12 4
> length(x)
[1] 3
> mode(x)
[1] "numeric"
> y<-"abc"
> y
[1] "abc"
> length(y)
[1] 1
> mode(y)
[1] "character"
> z<-c("abc", "28 c3")
> z
[1] "abc" "28 c3"
> length(z)
[1] 2
> mode(z)
[1] "character"
> z[3]<-"123"
> z
[1] "abc" "28 c3" "123"
> as.character(z[3])
[1] "123"
> as.integer(z[3])
[1] 123