作者celestialgod (天)
看板R_Language
标题Re: [问题] 两个变项合并为一
时间Mon Aug 10 15:32:29 2015
※ 引述《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
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 123.205.27.107
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/R_Language/M.1439191952.A.CF9.html
1F:推 zxas10143: 先跪在说,c大需要擦鞋洗脚吗XD擦鞋我拿手低~ 08/10 15:50
囧,拜托别这样... 我只是喜欢google跟解决问题而已XD
※ 编辑: celestialgod (123.205.27.107), 08/10/2015 16:12:22