R語言subset和merge函式的使用
阿新 • • 發佈:2019-02-09
1、merge函式對資料框的操作,從兩個資料框中選擇出條件相等的行組合成一個新的資料框
2、subset函式,從某一個數據框中選擇出符合某條件的資料或是相關的列
(1)單條件查詢
(2)指定顯示列
(3)多條件查詢
-
df1=data.frame(name=c("aa","bb","cc"),age=c(20,29,30),sex=c("f","m","f"))
-
df2=data.frame(name=c("dd","bb","cc"),age=c(40,35,36),sex=c("f","m","f"))
- mergedf=merge(df1,df2,by="name")
2、subset函式,從某一個數據框中選擇出符合某條件的資料或是相關的列
(1)單條件查詢
-
> selectresult=subset(df1,name=="aa")
-
> selectresult
-
name age sex
-
1 aa 20 f
-
> df1
-
name age sex
-
1 aa 20 f
-
2 bb 29 m
- 3 cc 30 f
(2)指定顯示列
-
> selectresult=subset(df1,name=="aa",select=c(age,sex))
-
> selectresult
-
age sex
- 1 20 f
(3)多條件查詢
-
> selectresult=subset(df1,name=="aa" & sex=="f",select=c(age,sex))
-
> selectresult
-
age sex
-
1 20 f
-
> df1
-
name age sex
-
1 aa 20 f
-
2 bb 29 m
- 3 cc 30 f