gpt4 book ai didi

reshape() function to make wide to long data(RESHAPE()函数使数据变宽变长)

转载 作者:bug小助手 更新时间:2023-10-24 17:54:57 26 4
gpt4 key购买 nike



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

I am trying to use reshape() function

我正在尝试使用reshape()函数


(due to some reasons, I can not use tidyverse function or other packages' function.
wanna use reshape() function)

(由于某些原因,我不能使用tidyVerse函数或其他包的函数。我想使用rehape()函数)


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

but it never works...

但它从来都不管用。


更多回答

There are several errors in your code: (1) there is no argument seperator, use sep = instead; (2) "wife" needs to be quoted; (3) you need to specify the varying = argument. What should the final output look like? Please include any error messages when code fails.

您的代码中有几个错误:(1)没有参数分隔符,请使用sep=;(2)需要用引号将“妻子”引起来;(3)需要指定Variing=参数。最终输出应该是什么样子的?当代码失败时,请包括任何错误消息。

优秀答案推荐

Here is the code:

以下是代码:


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"
)

Changes made:

所做的更改:



  1. Replaced seperator with varying to specify the variables to be reshaped.

  2. Used v.names to provide meaningful names for the reshaped variables.

  3. Changed timevar to "gender" to represent the different groups ("hus" and "wife").


更多回答

You could also have reshape guess the names - reshape(data, idvar="ID", direction="long", varying=-1, sep="_", timevar="gender") - though being explicit about the groupings can make it more error-proof.

您还可以重塑猜测名称-RESHAPE(data,idvar=“ID”,Direction=“long”,Variing=-1,Sep=“_”,Timevar=“Gender”)-尽管明确说明分组可以使其更具防错性。

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com