简体   繁体   English

R中字符串和字符有什么区别?

[英]What is the difference between string and character in R?

I'm not pretty familiar with R, but anyhow I'm writing a R wrapper for ac library. 我对R不是很熟悉,但无论如何我正在为ac库编写一个R包装器。 I come across this problem. 我遇到了这个问题。 How do I decide if the input argument is a string? 如何判断输入参数是否为字符串? In details,should I write like this: 在细节上,我应该这样写:

dyn.load("hello.so")
do_process <- function(str) {
        if(!is.character(str))
            stop("not a character or string");
    result <- .Call("hello", as.character(str))
    return result
}

or this: 或这个:

dyn.load("hello.so")
do_process <- function(str) {
        if(!is.string(str))
            stop("not a character or string");
    result <- .Call("hello", as.string(str))
    return result
}

Thanks. 谢谢。

is.string is a function from the xtable package. is.stringxtable包中的一个函数。 In the details section of the help page it explicitly says "These functions are private functions used by print.xtable. They are not intended to be used elsewhere." 在帮助页面的详细信息部分,它明确指出“这些函数是print.xtable使用的私有函数。它们不打算在别处使用。”

As such, I would avoid using those functions. 因此,我会避免使用这些功能。

In R there is no string data type. R中没有string数据类型。 Instead it is called character and you can use is.character to do the check you're describing. 相反,它被称为character ,您可以使用is.character进行您正在描述的检查。

Also, as I mentioned in my comment, avoid using important base functions as variable names. 另外,正如我在评论中提到的,避免使用重要的基本函数作为变量名。 Specifically str is used to view the structure of an object. 具体而言, str用于查看对象的结构。

In R, there's no fundamental distinction between a string and a character. 在R中,字符串和字符之间没有根本区别。 A "string" is just a character variable that contains one or more characters. “string”只是一个包含一个或多个字符的字符变量。

One thing you should be aware of, however, is the distinction between a scalar character variable, and a vector . 但是,您应该注意的一件事是标量字符变量和矢量之间的区别。 A character vector is a set of strings stored as a single object. 字符向量是一组存储为单个对象的字符串。 Most R functions that work on character input are vectorised, ie they will return the appropriate value for each element in such a vector. 大多数用于字符输入的R函数都是矢量化的,即它们将为这样的向量中的每个元素返回适当的值。

For example: 例如:

# a string containing one character
x <- "a"
nchar(x)
# 1

# a string containing multiple characters
x <- "foo"
nchar(x)
# 3

# a character vector: two strings, each containing three characters
x <- c("foo", "bar")

# length() returns the no. of elements in a vector, NOT the length of each string
length(x)
# 2

# nchar() returns the length of each string in a vector
nchar(x)
# 3 3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM