添加行至数据框
问题:
有时需要给数据框添加一行或者更多新行
结局方案:
创建第二个包含这些新行的临时数据框,然后调用rbind()函数将这个临时数据框添加到原始数据框后面:
> b
city country state pop
1 Chicago Cook IL 2853144
2 Kenosha Kenosha WI 90352
3 Aurora Kane IL 171782
4 Elgin Lake IL 94487
> newRow<-data.frame(city="Cicero",country="Cook",state="IL",pop=72616)
> newb<-rbind(b,newRow)
> newb
city country state pop
1 Chicago Cook IL 2853144
2 Kenosha Kenosha WI 90352
3 Aurora Kane IL 171782
4 Elgin Lake IL 94487
5 Cicero Cook IL 72616
选定数据框的列
根据列名
- dfrm[[“name”]]
- dfrm$name
- drrm[“name”]
- dfrm[c(“name1”,”name2”)]
- dfrm[,”name”]
- dfrm[c(“name1”,”name2”)]
根据subset()函数
- subset(dfrm,select=colname)
- subset(dfrm,select=c(colname1,colname2))
- subset(dfrm,subset=(response>0))其中response是数据框的一列,选择出response为正的行
> newb
city country state pop
1 Chicago Cook IL 2853144
2 Kenosha Kenosha WI 90352
3 Aurora Kane IL 171782
4 Elgin Lake IL 94487
5 Cicero Cook IL 72616
> subset(newb,select=pop)
pop
1 2853144
2 90352
3 171782
4 94487
5 72616
> subset(newb,select=pop,subset=(pop>171782))
pop
1 2853144
修改数据框的列名
- colnames(dfrm)<-newnames
> colnames(newb)<-c("ncity","ncountry","nstate","npop")
> newb
ncity ncountry nstate npop
1 Chicago Cook IL 2853144
2 Kenosha Kenosha WI 90352
3 Aurora Kane IL 171782
4 Elgin Lake IL 94487
5 Cicero Cook IL 72616
根据名称排除列
- 调用包含一个select参数值为负值的subset()函数:
subset(dfrm,select=-badboy)
> newb
ncity ncountry nstate npop
1 Chicago Cook IL 2853144
2 Kenosha Kenosha WI 90352
3 Aurora Kane IL 171782
4 Elgin Lake IL 94487
5 Cicero Cook IL 72616
> subset(newb,select=c(-ncity,-ncountry))
nstate npop
1 IL 2853144
2 WI 90352
3 IL 171782
4 IL 94487
5 IL 72616
合并两个数据框
- new<-cbind(dfrm1,dfrm2)
- new<-rbind(dfrm1,dfrm2)
根据共有列合并数据框
问题:
有两个数据框,有相同的列,也有不同的列。需要通过匹配共有列来合并它们的行,使之成为一个数据框。
解决方案:
调用merge()函数,基于共有列把这些数据框连接成一个新的数据框:
m<-merge(df1,df2,by=”name”)其中name是数据框共有的列名。
> born
name year.born place.born
1 Moe 1887 a
2 Larry 1902 b
3 Curly 1903 c
4 Harry 1964 d
> died
name year.died
1 Curly 1952
2 Moe 1975
3 Larry 1975
> merge(born,died,by="name")
name year.born place.born year.died
1 Curly 1903 c 1952
2 Larry 1902 b 1975
3 Moe 1887 a 1975
基本数据类型之间的转换
- as.character()
- as.complex()
- as.numberic()或者as.double()
- as.integer()
- as.logical()
不同结构化数据类型间的转换
- as.data.frame()
- as.list()
- as.matrix()
- as.vector()