repeat()函数将宽数据转换为长数据

w6lpcovy  于 2023-09-27  发布在  其他
关注(0)|答案(1)|浏览(85)
set.seed(123)
data <- data.frame(ID = 1:10,
                   weight_hus = rnorm(10, 0, 1),
                   weight_wife = rnorm(10, 0, 1),
                   height_hus = rnorm(10, 0, 1),
                   height_wife = rnorm(10, 0, 1))

我正在尝试使用reshape()函数
(due由于某些原因,我不能使用tidyverse函数或其他软件包的函数。repeat()函数

data2 <- reshape(data = data,
                 idvar = "ID",
                 seperator = "_",
                 direction = "long",
                 v.name = c("body"),
                 timevar = c("hus", wife)
               )

但从来都不管用

nfg76nw0

nfg76nw01#

代码如下:

set.seed(123)
data <- data.frame(ID = 1:10,
                   weight_hus = rnorm(10, 0, 1),
                   weight_wife = rnorm(10, 0, 1),
                   height_hus = rnorm(10, 0, 1),
                   height_wife = rnorm(10, 0, 1))

data2 <- reshape(data = data,
                 idvar = "ID",
                 varying = list(c("weight_hus", "weight_wife"), c("height_hus", "height_wife")),
                 v.names = c("weight", "height"),
                 direction = "long",
                 times = c("hus", "wife"),
                 timevar = "gender"
               )

所做的更改:
1.将seperator替换为varying,以指定要整形的变量。
1.使用v.names为整形后的变量提供有意义的名称。
1.将timevar更改为“性别”,以表示不同的组(“丈夫”和“妻子”)。

相关问题