作者tony255034 (5245566)
看板R_Language
标题[问题] 行转列的方式
时间Thu Oct 1 21:31:31 2015
[问题类型]:
程式谘询(我想用R 做某件事情,但是我不知道要怎麽用R 写出来)
效能谘询(我想让R 跑更快)
[软体熟悉度]:
*[1;30;40m
新手(没写过程式,R 是我的第一次)
[问题叙述]:
请简略描述你所要做的事情,或是这个程式的目的
所附的程式码有成功将上面的格式转为下面的格式
但想请教的是dylpr或R的语法中有没有更简洁撰写的方式呢?
name sex score1 score2 score3
1 sally f 100 23 24
2 tony m 52 32 45
3 sam m 65 42 34
转成
name sex score value
1 sally f score1 100
2 sally f score2 23
3 sally f score3 24
4 tony m score1 52
5 tony m score2 32
6 tony m score3 45
7 sam m score1 65
8 sam m score2 42
9 sam m score3 34
[程式范例]:
d1 <- data.frame(d[1:2])
d1 <- d1[rep(seq_len(nrow(d1)), each=3)]
col <- str_pad(c(1:3),2,"left",'0')
d1 <- mutate(d1, SCORE = rep(col,length(d[[1]])))
d2 <- data.frame(t(d[3:5]),stringsAsFactors = FALSE)
temp <- stack(d2)
temp[2] <- NULL
d1 <- cbind(d1,temp)
[环境叙述]:
win7 32bit 4G R 3.1.2
[关键字]:
Column to Row, dplyr
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 123.195.74.150
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/R_Language/M.1443706294.A.C6B.html
2F:→ andrew43: 用 melt() 大概是最常看到的方法。 10/01 21:34
3F:→ andrew43: 可用「wide to long data table R」当关键字。 10/01 21:36
4F:→ celestialgod: tidyr才有 dplyr没有 10/01 21:49
5F:→ celestialgod: gather 10/01 21:50
6F:→ celestialgod: gather(d1, score, value, -name, - sex) 10/01 22:02
7F:→ andrew43: 喔好像是经纬度。as.factor(paste(经度, 纬度)) 10/01 23:19
8F:→ andrew43: 推错 10/01 23:20