把数据输入R之后,如何进行简单的操作(一)

作者:丁点helper

来源:丁点帮你

回忆一下上一讲用到的例子:

输入数据的代码在上一讲详细讲解过,这里总结如下:

age <- c(25, 34, 59, 60, 20)   
#患者年龄type <- c(1, 2, 2, 2, 1)       
#糖尿病类型status <- c("poor", "improved", "excellent", "poor", "excellent")  
#病情comorbidity<- c(TRUE, FALSE, FALSE, TRUE, FALSE)   
#出现并发症

age、type、status、comorbidity中分别仅有一种数据类型,它们都是向量。本文介绍生成向量之后,如何对其进行简单的操作。

1. 查看与改变向量的数据类型
看到一个向量,首先要搞清楚其中包含的数据类型。就本例而言,从表面看也很容易区分,但实际上一项统计分析工作用到的向量可能很多,用函数class()可以快速知晓某向量的数据类型,例如:

class(age) [1]
"numeric"class(type) [1] 
"numeric"class(status) [1]
"character"class(comorbidity)[1]
"logical"

不同类型的数据可以根据需要互相转换,用as.目标数据类型()函数:

as.numeric() 
#将括号中的内容转变为数值型数据
as.character() 
#转变为字符型as.logical()  
#转变为逻辑型as.factor()    
#转变为因子型

所以也可用as.character()将type中的数值型数据转变为字符型:

type[1] 
1 2 2 2 1class(type) [1] 
"numeric"
type <- as.character(type)   
# 注意要将新的结果赋值给typetype[1] "1" "2" "2" "2" "1"class(type)[1] "character"

之前讲过,将定性变量(即分类变量)以因子的形式输入会有助于后续的统计分析工作,factor()这个函数可以帮我们把数据转变为因子型:

type <- c(1, 2, 2, 2, 1) 
type <- factor(type)
type[1] 
1 2 2 2 1
Levels: 1 2class(type)[1]
"factor"

用1和2这样的阿拉伯数字其实不太利于准确地表达数据内容,可以给原来的1和2加上标签:

type <- factor(type, levels = c("1", "2"), 
               labels = c("Type 1", "Type 2")) 
type[1] 
Type 1 Type 2 Type 2 Type 2 Type 1
Levels: Type 1 Type 2

所以在输入定性变量(分类变量)时可以采用这种简便方法。

再看另一个例子:

status[1]
"poor"
"improved" 
"excellent"
"poor" 
"excellent"
status <- factor(status)status[1] 
poor  improved  excellent poor  excellentLevels: 
excellent improved poorclass(status)[1]
"factor"

由于status是一个有序分类变量,所以在转变为因子时还应体现其顺序:

status <- factor(status, levels = c('poor', 'improved','excellent'),ordered = TRUE) 
status[1] 
poor  improved  excellent 
poor  excellentLevels:
poor < improved < excellent
这里的顺序是根据levels这个命令中的内容生成的,可自行调整levels命令中的顺序:
status <- factor(status, levels = c('excellent','improved' ,'poor'),ordered = TRUE)
status[1]
poor improved  excellent 
poor  excellentLevels: 
excellent < improved < poor

2. 向量中的数据定位

以age这个向量为例:

age <- c(25, 34, 59, 60, 20) 
age
[1] 25 34 59 60 20

输出向量中排在第3位的数据:

age[3]
[1] 59

输出排在1,2,5位的数据:

age[c(1,2,5)]
[1] 25 34 20

输出1至3位的数据:

age[c(1:3)]  
[1] 25 34 59

3. 向量中的数据计算

以age这个向量为例:

age <- c(25, 34, 59, 60, 20)
# 仍以age为例age
[1] 25 34 59 60 20
age+4       
# 给向量中每个数都加4
[1] 29 38 63 64 24
sqrt(age)   
# 求平方根
[1] 5.000000 5.830952 7.681146 7.745967 4.472136
sort(age)   
# 给数据从低到高排序
[1] 20 25 34 59 60
sort(age, decreasing =T)    
# 给数据从高到低排序
[1] 60 59 34 25 20
age2 <- c(20,30,40,50,60)   
# 再生成一个向量  
age+age2    
# 将两向量中的元素相加
[1]  45  64  99 110  80

4. 生成特定形式的向量

生成重复数据。用rep(x, ……),x表示要重复的内容。

rep(1,times=5)   
#times表示重复的次数
[1] 1 1 1 1 1
rep(c(1,2),4)   
#times这个表达可以省略
[1] 1 2 1 2 1 2 1 2
rep(c(1,2),each=4)   
#each也是针对重复次数的命令
[1] 1 1 1 1 2 2 2 2

特定间隔的数据。用seq(from,to,by)这个函数,from为起始值,to为终止值,by为数据之间的间隔。

seq(1,100,19)  
#from,to,by都可以省略 
[1]  1 20 39 58 77 96
seq(1,10)   
#如果不指定by的内容,则默认为1
[1]  1  2  3  4  5  6  7  8  9 10

下一篇介绍数据框的相关操作。

猜你喜欢

转载自blog.csdn.net/yoggieCDA/article/details/108400434