KnitR:控制台和PDF之间的输出差异(编码)

时间:2014-01-25 05:14:01

标签: r character-encoding knitr

首先,我有2个大小为15的向量: lb_result:

cap-color               
cap-color               
odor                    
odor                    
odor                    
odor                    
gill-spacing            
gill-size               
gill-color              
stalk-surface-above-ring
stalk-color-above-ring  
spore-print-color       
spore-print-color       
population              
population 

和: vl_result:

buff     
pink     
creosote 
foul     
musty    
pungent  
close    
narrow   
buff     
silky    
cinnamon 
chocolate
green    
scattered
several 

现在,我希望输出为:

cap-color ∈ {buff, pink}
odor ∈ {creosote, foul, musty, pungent}
gill-spacing = {close}
gill-size = {narrow}
gill-color = {buff}
stalk-surface-above-ring = {silky}
stalk-color-above-ring = {cinnamon}
spore-print-color ∈ {chocolate, green}
population ∈ {scattered, several}

我写了一个Rscript:

dt <- data.table("Name"=lb_result,"Var"=vl_result)  
  res <- dt[,paste(Var,collapse=","),by=Name]

  for(i in 1:length(res$V1)){
  if (length(grep(",",res$V1[i],value=T)) == 0) {
    res$V1[i] = paste("= ", res$V1[i])
  } else
    # {res$V1[i] = paste(" \u2208 {", res$V1[i], "}")}
    {res$V1[i] = paste(" ∈ {", res$V1[i], "}")}
  }


  for(i in 1:length(res$V1)){
    print(paste(res$Name[i],res$V1[i]))
  }

在Consol R中,我得到了结果:

[1] "cap-color  ∈ { buff,pink }"
[1] "odor  ∈ { creosote,foul,musty,pungent }"
[1] "gill-spacing =  close"
[1] "gill-size =  narrow"
[1] "gill-color =  buff"
[1] "stalk-surface-above-ring =  silky"
[1] "stalk-color-above-ring =  cinnamon"
[1] "spore-print-color  ∈ { chocolate,green }"
[1] "population  ∈ { scattered,several }"

但是,当我在文件中插入此Rscript时。 Rnw with knitR。

PDF文件输出:

它显示<U+2208>而不是∈

1 个答案:

答案 0 :(得分:1)

此问题至少有两个级别的编码。你必须确保两者都是正确的。第一级是Rnw文件的文件编码,您需要将其传递给knit(..., encoding = "Your File Encoding")。第二级是LaTeX中的编码规范,通常是通过inputenc包。例如,如果编码为UTF-8,则为\usepackage[utf8]{inputenc}

如果您通过例如source()将其作为独立文件执行,则可以存在第三级文件编码,即R脚本的编码。如果没有更多详细信息(如操作系统,文本编辑器以及调用knitr的方式),则很难诊断问题。至少你需要包括

library(knitr)
sessionInfo()