Re: [問題] 一筆資料轉多筆

看板R_Language作者 (cywhale)時間7年前 (2016/12/01 23:50), 編輯推噓4(406)
留言10則, 4人參與, 最新討論串5/7 (看更多)
手癢也試了一下,就用data.table::foverlaps做 ## data.table::foverlaps, reference: #1N_NLOIo library(data.table) library(magrittr) dt <- fread('id start_y start_s end_y end_s 1 100 1 102 2 2 101 2 103 1 3 101 2 101 2') %>% .[,{.(id=id, start=as.numeric(paste(start_y,start_s,sep=".")), end = as.numeric(paste(end_y,end_s,sep=".")))}] %>% setkey(start,end) gt <- CJ(start_y=100:103, s=1:2) %>% .[,{.(start=as.numeric(paste(start_y,s,sep=".")))}] %>% unique() %>% .[,end:=start] gx <- foverlaps(gt, dt, type="within", which=TRUE) %>% .[which(!is.na(yid)),] cbind(dt[gx$yid,.(id)], gt[gx$xid,.(start)]) %>% .[order(id),] %>% .[,{.(id=id, year=substr(start,1,nchar(start)-2), s=substr(start,nchar(start),nchar(start)) )}] # id year s # 1: 1 100 1 # 2: 1 100 2 # 3: 1 101 1 # 4: 1 101 2 # 5: 1 102 1 # 6: 1 102 2 # 7: 2 101 2 # 8: 2 102 1 # 9: 2 102 2 #10: 2 103 1 #11: 3 101 2 ※ 引述《criky (立業成家)》之銘言: : [問題類型]: : : 程式諮詢(我想用R 做某件事情,但是我不知道要怎麼用R 寫出來) : [軟體熟悉度]: : 新手(沒寫過程式,R 是我的第一次) : [問題敘述]: : 若我有資料欄位如下: : : id start_y start_s end_y end_s : 1 100 1 102 2 : 2 101 2 103 1 : 3 101 2 101 2 : year: : 如何轉成下面的樣子: : id year s : 1 100 1 : 1 100 2 : 1 101 1 : 1 101 2 : 1 102 1 : 1 102 2 : 2 101 2 : 2 102 1 : 2 102 2 : 2 103 1 : 3 101 2 (只有一筆) : 謝謝回答~ : [程式範例]: : : : [環境敘述]: : : 請提供 sessionInfo() 的輸出結果, : 裡面含有所有你使用的作業系統、R 的版本和套件版本資訊, : 讓版友更容易找出錯誤 : : [關鍵字]: : : 選擇性,也許未來有用 : -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 36.225.167.251 ※ 文章網址: https://www.ptt.cc/bbs/R_Language/M.1480607402.A.8BD.html

12/01 23:56, , 1F
最後一行應該用tstrsplit就好
12/01 23:56, 1F

12/01 23:57, , 2F
CJ 好酷!!
12/01 23:57, 2F

12/01 23:59, , 3F
CJ在某種意義上是expand.grid,真是有趣的函數
12/01 23:59, 3F

12/02 00:05, , 4F
謝謝cy大,這篇解答好多括號= =
12/02 00:05, 4F

12/02 00:07, , 5F
忘了還有tstrsplit 感謝提醒~~ ^^
12/02 00:07, 5F

12/02 00:07, , 6F
我幫忙排成簡單易懂的好了@@
12/02 00:07, 6F

12/02 00:08, , 7F
算了,跟我習慣不同XDD
12/02 00:08, 7F

12/02 00:17, , 8F
XDD 沒關係 括號Rstudio會take care 我也常看不懂
12/02 00:17, 8F

12/02 00:18, , 9F
別人的排版<-其實是自己怪,另推data.table J, SJ, CJ好用
12/02 00:18, 9F

12/02 11:37, , 10F
你的排版真堅持
12/02 11:37, 10F
文章代碼(AID): #1OG4QgYz (R_Language)
討論串 (同標題文章)
文章代碼(AID): #1OG4QgYz (R_Language)