[英]R recode variable - unexpected INCOMPLETE_STRING
我试图在R中重新编码一个因子变量并使用以下代码:
library(car)
napier_captureComplexity=recode(napier$a_SpatialConnectivity,"'1 - Very simple and clear: no diagrams, single sheets'=1;'2 - Reasonably simple: some simple diagrams or second sheets'=2;'3 - Reasonably complex: multiple diagrams or sheets but can be followed'=3;'4 - Moderately complex: multiple diagrams and sheets'=4;'5 - Very complex'=5;",as.factor.result=FALSE)
并收到以下错误消息:
Error in parse(text = range[[1]][1]) : <text>:1:1: unexpected INCOMPLETE_STRING 1: '4 - Moderately complex
低于数字4的^
我不确定是什么导致这种情况,我想知道:通过代码,但我没有使用c(),并且代码在数据集中具有类似字符串值的其他因素上执行得很好。
任何帮助表示赞赏!
这实际上是因为你的描述中有“:”。 此函数使用一些奇数eval
和strsplit
语句来工作。 它最终在“:”中分裂,因为这是它们语法中的特殊代码,似乎没有办法逃脱它。
但我假设napier$a_SpatialConnectivity
是这些给定水平的一个因素? 您可以通过在factor()
调用中显式设置级别来重新编码变量。
mylevels <- c("1 - Very simple and clear: no diagrams, single sheets",
"2 - Reasonably simple: some simple diagrams or second sheets",
"3 - Reasonably complex: multiple diagrams or sheets but can be followed",
"4 - Moderately complex: multiple diagrams and sheets",
"5 - Very complex")
napier_captureComplexity <- as.numeric(factor(napier$a_SpatialConnectivity, levels=mylevels))
这将订购1:5的水平,恰好就是你试图重新编码它们的方式。
recode
似乎解释了:表示一系列值,即使它在一个字符串中,并且:被解释为过早地终止该字符串。 例如:
x = c("a","b","c")
recode(x, "'a'=1; 'b'=2; 'c'=3;")
[1] 1 2 3
但
x = c("a:d","b","c")
recode(x, "'a:d'=1; 'b'=2; 'c'=3;")
Error in parse(text = range[[1]][1]) :
<text>:1:1: unexpected INCOMPLETE_STRING
1: 'a
^
在每个例子中,我都试过字符串终止于:,导致错误。
任何处于类似位置但使用字符串而不是因子的人都应该能够使用gsub
从数据中删除冒号。
napier_captureComplexityy <- gsub(":","",napier$a_SpatialConnectivity)
从recode
字符串中省略冒号,它应该是好的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.