我试图在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)
Run Code Online (Sandbox Code Playgroud)
并收到以下错误消息:
Error in parse(text = range[[1]][1]) : <text>:1:1: unexpected INCOMPLETE_STRING 1: '4 - Moderately complex
Run Code Online (Sandbox Code Playgroud)
低于数字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))
Run Code Online (Sandbox Code Playgroud)
这将按照 1:5 的顺序对级别进行排序,这恰好是您尝试重新编码它们的方式。
recode似乎将 : 解释为表示一系列值,即使它位于字符串内,并且 : 被解释为过早终止字符串。例如:
x = c("a","b","c")
recode(x, "'a'=1; 'b'=2; 'c'=3;")
[1] 1 2 3
Run Code Online (Sandbox Code Playgroud)
但
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
^
Run Code Online (Sandbox Code Playgroud)
在每个示例中,我都尝试过字符串以 : 结尾,从而导致错误。