【问题标题】:How do I refer to defined objects using the reshape function in R?如何使用 R 中的 reshape 函数引用定义的对象?
【发布时间】:2017-10-25 17:51:54
【问题描述】:

我无法让 reshape 函数 ( stats::reshape ) 在其参数之一中接受对已定义字符向量的引用。我不知道这是否反映了我的错误语法、功能的限制,或者与 R 本身如何运作有关的更普遍的问题。

我正在使用 reshape 将数据从宽格式更改为长格式。我有一个包含许多重复测量的数据集,这些测量针对重塑(x.1、x.2、x.3、y.1、y.2、y.3 等)进行了适当的排序。我已经定义了一个变量firstlastmeasure,其中包含需要通过reshape处理的重复测量数据的第一列和最后一列的索引(这是为了防止每次从原始添加或删除列时都必须更改索引数据)。

这是它的定义方式(以一种复杂的方式):

temp0 <- subset(p, select=nameoffirstcolumn:nameoflastcolumn)
lastmeasname = names(temp0[ncol(temp0)])
firstmeasname = names(temp0[1])
firstmeasindex = grep(firstmesname,colnames(p))
lastmeasindex = grep(lastmesname,colnames(p))
firstlastmeasure <- paste(firstmesindex,lastmesindex,sep=":")

我使用这个变量作为 reshape 的 varying 参数的参数,如下所示:

reshape(dataset, direction = "long", varying = firstlastmeasure)

重塑总是返回:

“猜测错误(变化):无法从名称中猜测时变变量”。

明确使用数字索引(即varying = 6:34)可以正常工作。

【问题讨论】:

  • 你能让你的例子可重现吗?分享足够的数据来说明问题?此外,reshape2 包中没有名为 reshape 的函数。 reshape2 具有 meltcastdcastrecast 作为主力功能。我假设您使用的是内置的stats::reshape
  • 请提供定义firstlastmeasure的代码。
  • 这听起来也不像是您正确使用了varying 参数,从?stats::reshapevarying 被描述为“宽格式变量集的名称[或索引]对应于长格式的单个变量。”我没有从你对firstlastmeasure 的描述中明白这一点。而不是“重复测量的第一列和最后一列的索引”,你能做到index_to_first:index_to_last吗?
  • 对不起,这实际上是内置的重塑功能,我已经解决了这个问题。
  • @Gregor 这确实有效,谢谢!所以就我定义的对象而言,它是:varying=firstmeasindex:lastmeasindex 有效

标签: r reshape


【解决方案1】:

paste 创建一个字符串,如果您查看firstlastmeasure,它将类似于"6:34"。如果您查看6:34,它将是一个向量6 7 8 9 ... 34。您需要定义向量,而不是将字符串粘贴在一起。 (请注意,subset 进行了一些特殊处理以使 : 与列名一起使用。)

如果我正确解释了您的代码,temp0 拥有您想要的所有列,所以您可以这样做

firstlastmeasure = names(temp0)

并完成它。稍微复杂一点,你可以保留grep 代码而不使用paste

firstlastmeasure = firstmeasindex:lastmeasindex

由于您输入的是姓名,所以subset 是不必要的。最简单的方法是跳过temp0 并执行

firstlastmeasure = grep(nameoffirstcolumn, names(p)):grep(nameoflastcolumn, names(p))

【讨论】:

    猜你喜欢
    • 2018-10-09
    • 2022-06-10
    • 1970-01-01
    • 2014-11-14
    • 1970-01-01
    • 2014-10-10
    • 2017-10-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多