R:自动复制大量数据
R: automatically copy large amounts of data
我是 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
顺序与您发布的顺序略有不同——先回答所有 "Yes" 个问题,然后再回答 "No" 个问题,而不是交替进行。
我是 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
顺序与您发布的顺序略有不同——先回答所有 "Yes" 个问题,然后再回答 "No" 个问题,而不是交替进行。