Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/41.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何计算R中的nchar?_R_Char - Fatal编程技术网

如何计算R中的nchar?

如何计算R中的nchar?,r,char,R,Char,我尝试以下代码 j <- "*Politics:* Disgraced peer Jeffrey Archer is set to make \xa31m from his Belmarsh " nchar(j) # Error in nchar(j) : invalid multibyte string 1 正如你所看到的,我不能使用nchar。我如何解决这个问题?如果Dason是正确的 我知道只有一种方法可以做到这一点,它需要使用readLines读取中的每个字符串: n=2表示你在

我尝试以下代码

j <- "*Politics:* Disgraced peer Jeffrey Archer is set to make \xa31m from his Belmarsh "
nchar(j)
# Error in nchar(j) : invalid multibyte string 1
正如你所看到的,我不能使用nchar。我如何解决这个问题?

如果Dason是正确的

我知道只有一种方法可以做到这一点,它需要使用readLines读取中的每个字符串:

n=2表示你在读两行。 然后在我使用的rgui中的contr+r或r studio中的cntrl+enter中阅读它们。
然后,如果您知道具体的编码,您可以使用nchar,您可以使用iconv转换为更好的编码

j <- "*Politics:* Disgraced peer Jeffrey Archer is set to make \xa31m from his Belmarsh "
iconv(j, "ISO-8859-1", "UTF-8")
#[1] "*Politics:* Disgraced peer Jeffrey Archer is set to make £1m from his Belmarsh "
nchar(iconv(j, "ISO-8859-1", "UTF-8"))
#[1] 79

我建议您阅读nchar?nchar上的帮助文件,因为默认类型和type=bytes之间存在细微差异。

为什么不能使用nchar?当你这样做的时候,你会出错吗?如果是,错误是什么?你能输出多少个字符?你希望输出什么?你使用了什么代码?错误是什么?发布你使用的代码比你所做的部分图片更有帮助,也更有可能得到回复。是的,我收到了一个错误。我将字符设置为x并写入ncharx。R显示了一个错误,没有结果。请发布您在问题中使用的确切代码。包括您尝试过的字符串。我编辑了您的问题,以便于人们帮助。如果我搞砸了,请随意编辑,但我强烈建议您不要将内容发布为不需要是图像的图像,并且始终包含感兴趣的错误输出。我认为这就是问题所在,我认为转义字符是问题所在。只有当编码每个字符使用一个字节时,你计算字节数的另一种方法才会起作用——只有你能找出编码,你才能理解这一点!在这里,我没有理由投反对票,因为我只回答了一个很小的问题。这个解决方案解决了我当时认为的问题。我在Dason回答之前回答了,Dason的评论是关于他对OP的模糊问题所做的编辑。原文甚至没有代码,只有文本的图片。在Dason的回答之后,我把它留给了a和b,因为OP从未编辑他们的回答,Dason做的是为了弄清楚,所以实际问题是未知的。我所要求的是你在投票时花上4秒或更多的时间思考,因为这不是facebook。这可能会帮助你在未来更好地投票:
j <- "*Politics:* Disgraced peer Jeffrey Archer is set to make \xa31m from his Belmarsh "
iconv(j, "ISO-8859-1", "UTF-8")
#[1] "*Politics:* Disgraced peer Jeffrey Archer is set to make £1m from his Belmarsh "
nchar(iconv(j, "ISO-8859-1", "UTF-8"))
#[1] 79
nchar(j, type = "bytes")
#[1] 79