R:自动复制大量数据

标签 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)

我该怎么办?

最佳答案

我将使用“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

顺序与您发布的顺序略有不同 - 首先回答所有"is",然后回答“否”,而不是交替回答。

关于R:自动复制大量数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29886259/

相关文章:

python - 如何按照我需要的方式 reshape 这个数组?

r - 如何 reshape 数据框以生成两列值(R 编程)

r - 折叠连续整数到范围的字符串

r - 您可以在 R 中使用 apply 实现 'sweep' 吗?

reshape multi id repeated variable readings 从长到宽

python - 新数组的总大小必须不变

r - 使用 dplyr 和 tidyr 制作更复杂的表

r - ForceNetwork 未显示,未返回代码错误

r - 在 R-Server Ubuntu 上安装 rgl

r - 如何在功能上传播和合并数据