R:自动复制大量数据

时间:2015-04-27 02:32:09

标签: r reshape

我是R的新手,我有一些这样的数据:

Yes No age    color  place
12  5  12-18  red    right
2   33 19-30  yellow left
...

我需要创建新数据库,

answer   age    color  place
Yes      12-18  red    right 
Yes      12-18  red    right
...                          (12 times)

No       12-18  red    right
No       12-18  red    right
...                          (5 times)

我该怎么办?

1 个答案:

答案 0 :(得分:4)

我会使用来自我的" splitstackshape"的expandRows的组合。包和来自" reshape2"。

melt

假设您的数据被调用" mydf",请尝试:

library(splitstackshape)
library(reshape2)
dfLong <- expandRows(
  melt(mydf, measure.vars = c("Yes", "No"), 
       variable.name = "answer"), "value")

以下是前20行:

head(dfLong, 20)
#        age  color place answer
# 1    12-18    red right    Yes
# 1.1  12-18    red right    Yes
# 1.2  12-18    red right    Yes
# 1.3  12-18    red right    Yes
# 1.4  12-18    red right    Yes
# 1.5  12-18    red right    Yes
# 1.6  12-18    red right    Yes
# 1.7  12-18    red right    Yes
# 1.8  12-18    red right    Yes
# 1.9  12-18    red right    Yes
# 1.10 12-18    red right    Yes
# 1.11 12-18    red right    Yes
# 2    19-30 yellow  left    Yes
# 2.1  19-30 yellow  left    Yes
# 3    12-18    red right     No
# 3.1  12-18    red right     No
# 3.2  12-18    red right     No
# 3.3  12-18    red right     No
# 3.4  12-18    red right     No
# 4    19-30 yellow  left     No

## Confirm that there are the correct number of combinations
table(dfLong$age, dfLong$answer)
#        
#         Yes No
#   12-18  12  5
#   19-30   2 33

订单与您发布的内容略有不同 - 做好所有&#34;是&#34;首先回答然后回答&#34;否&#34;答案而不是在他们之间交替。