Re: [问题] 两个变项合并为一

楼主: celestialgod (天)   2015-08-10 15:32:29
※ 引述《zxas10143 (~无言以对~)》之铭言:
: [软件熟悉度]:
: 入门(写过其他程式,只是对语法不熟悉
: 各位高手好
: 小的想请教前辈们如何将变项X与变项Y合并为变项Z
: 如下:
: x y z(合并后)
: 1 NA 1
: 2 NA 2
: NA 5 5
: 3 NA 3
: NA 8 8
: 用STATA的语言就是 egen z=rowfirst( x y )
: 不知道R是怎么做的呢?
: 还烦请前辈们解惑
五种方法任君挑选^^"
## naive method
dat = data.frame(x = c(1,2,NA,3,NA), y = c(NA,NA,5,NA,8))
dat$z = dat$x
dat$z[is.na(dat$x)] = dat$y[is.na(dat$x)]
## cool method
dat = data.frame(x = c(1,2,NA,3,NA), y = c(NA,NA,5,NA,8))
dat$z = ifelse(is.na(dat$x), dat$y, dat$x)
## more elegant
dat = data.frame(x = c(1,2,NA,3,NA), y = c(NA,NA,5,NA,8))
dat$z = with(dat, ifelse(is.na(x), y, x))
## tricky but helpful for three or more columns
dat = data.frame(x = c(1,2,NA,3,NA), y = c(NA,NA,5,NA,8))
dat$z = na.omit(c(unlist(t(dat))))
## only available for numeric columns
dat = data.frame(x = c(1,2,NA,3,NA), y = c(NA,NA,5,NA,8))
dat$z = rowSums(dat, TRUE)
benchmark: http://pastebin.com/z03vffti
我一般都用2或3... 虽然看起来benchmark是比较没效率XDDDD (但是都很快就是)
但是在dplyr中使用的话,比较方便
搭配data.table也比较不会有复制资料的问题
4跟5是我google到的方法,欢迎参考看看。
reference: http://tinyurl.com/nzjtxea
作者: zxas10143 (~无言以对~)   2015-08-10 15:50:00
先跪在说,c大需要擦鞋洗脚吗XD擦鞋我拿手低~

Links booklink

Contact Us: admin [ a t ] ucptt.com