Re: [問題] 在R裡面的if then output寫法?

作者: raydai (Ray)   2018-01-16 02:28:35
※ 引述《paranoia5201 (社會黑暗、行路難)》之銘言:
: [問題類型]:
: 程式諮詢(我想用R 做某件事情,但是我不知道要怎麼用R 寫出來)
: [軟體熟悉度]:
: 入門(寫過其他程式,只是對語法不熟悉)
: [問題敘述]:
: 以下是一個SAS的簡單程式,想問在R中要如何也做出同樣的事情。
: 這裡是針對if then "output"的部分。
: 若需要先下載某packages也請直說!
: [程式範例]:
: data m0 m1 m2;
: set mor;
: keep year sex areaname_new ADJ_R TotalCase;
: if type = "綜合" & areaname_new = "全國" ;
: if sex = "0" then output m0;
: if sex = "1" then output m1;
: if sex = "2" then output m2;
: run;
: [環境敘述]:
: R3.2.3
: [關鍵字]:
: 初學者經驗?
我也很久沒有使用SAS,不過對於我的理解,我就想到這樣寫.或許有更容易的寫法
提供給你參考
==================================================================================
## create a fake dataset
mydata<-data.frame("year"=c(1986,2012,2013,2020,2019,1999,1986,2012,2013,2020,2019,1999),
"type"=rep(c("A","B"),6),
"sex"=rep(c("male","female"),6),
"areaname_new"=rep(c("global","local"),6),
"ADJ_R"=rnorm(n =12,mean = 0,sd = 1),
"TotalCase"=rnorm(n = 12,mean = 5,sd = 1.5))
library("dplyr") ## Data manupulation
## Assinge the data to a new varaible "m0"
## %>% this is pipe function from "dplyr" package.
mydata%>%filter(type=="A",areaname_new=="global",sex=="male")%>% ## filter
select("year", "sex" ,"areaname_new" ,"ADJ_R", "TotalCase")%>% ## Keep the variables you want
assign("m0",value =.,envir =.GlobalEnv ) ## Assign the dataset to a new varaible
==========================================================================================

Links booklink

Contact Us: admin [ a t ] ucptt.com