[英]How do I refer to defined objects using the reshape function in R?
我无法获得重整形函数(stats :: reshape)以在其参数之一中接受对已定义字符向量的引用。 我不知道这是否反映了我的语法错误,功能限制或与R本身的运行方式有关的更一般的问题。
我正在使用整形将数据从宽格式更改为长格式。 我有一个包含许多重复度量的数据集,这些度量针对重塑进行了适当排序(x.1,x.2,x.3,y.1,y.2,y.3等)。 我定义了一个变量firstlastmeasure
,该变量包含需要通过重firstlastmeasure
处理的重复测量数据的第一列和最后一列的索引(这是为了避免每次在原始数据中添加或删除列时都必须更改索引) 。
这是它的定义方式(以复杂的方式):
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=":")
我将此变量用作重塑varying
参数的参数,如下所示:
reshape(dataset, direction = "long", varying = firstlastmeasure)
重塑总是返回:
“猜测(变量)错误:无法从名称中猜测随时间变化的变量”。
显式使用数字索引(即, varying = 6:34
)效果很好。
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.