将值列扩展为分类数据

时间:2017-03-03 03:06:34

标签: r tidyr

我有ffff<-data.frame(dest = c("NY", "NY", "LA", "LA"), st_ti = c("ok", "bad", "ok", "bad"), qty = c(2,2,2,1))

ff

dest st_ti qty 1 NY ok 2 2 NY bad 2 3 LA ok 2 4 LA bad 1

gg<-data.frame(dest = c("NY", "NY", "NY", "NY", "LA", "LA","LA"), 
st_ti = c("ok", "ok", "bad", "bad", "ok", "ok", "bad"))

我想扩展所有分类数据,如下所示:

gg:

dest st_ti 1 NY ok 2 NY ok 3 NY bad 4 NY bad 5 LA ok 6 LA ok 7 LA bad

gather

我想从tidyr包中执行类似use yii\helpers\HtmlPurifier;的操作,但我不相信此选项可用。

2 个答案:

答案 0 :(得分:4)

您可以通过 qty 列重复行名称,然后选择具有扩展行名称的行:

ff[rep(rownames(ff), ff$qty), c("dest", "st_ti")]

#    dest st_ti
#1     NY    ok
#1.1   NY    ok
#2     NY   bad
#2.1   NY   bad
#3     LA    ok
#3.1   LA    ok
#4     LA   bad

要重置rownames:

ff1 <- ff[rep(rownames(ff), ff$qty), c("dest", "st_ti")]
rownames(ff1) <- NULL
ff1

#  dest st_ti
#1   NY    ok
#2   NY    ok
#3   NY   bad
#4   NY   bad
#5   LA    ok
#6   LA    ok
#7   LA   bad

答案 1 :(得分:2)

我们可以使用expandRows

执行此操作
library(splitstackshape)
setDT(expandRows(ff, 'qty'))[]
#   dest st_ti
#1:   NY    ok
#2:   NY    ok
#3:   NY   bad
#4:   NY   bad
#5:   LA    ok
#6:   LA    ok
#7:   LA   bad