Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/68.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';s strplit()函数:添加索引值有什么区别?_R_Strsplit - Fatal编程技术网

在R';s strplit()函数:添加索引值有什么区别?

在R';s strplit()函数:添加索引值有什么区别?,r,strsplit,R,Strsplit,我正在学习R,我从一个练习中得到了以下代码,目标是编写代码,计算rquote中第一个u之前的R的数量 rquote <- "r's internals are irrefutably intriguing" chars <- strsplit(rquote, split = "")[[1]] # Initialize rcount rcount <- 0 # Finish the for loop for (char in chars

我正在学习R,我从一个练习中得到了以下代码,目标是编写代码,计算
rquote
中第一个u之前的R的数量

rquote <- "r's internals are irrefutably intriguing"
chars <- strsplit(rquote, split = "")[[1]]

# Initialize rcount
rcount <- 0

# Finish the for loop
for (char in chars) {
  if (char == "r"){
      rcount = rcount + 1
  }
  if (char == "u"){
      break
  }
  
}

# Print out rcount
print(rcount)

当您使用或不使用
[[1]]
时,
字符
是不同的

使用
[[1]]
时:

chars1 <- strsplit(rquote, split = "")[[1]]
chars1
# [1] "r" "'" "s" " " "i" "n" "t" "e" "r" "n" "a" "l" "s" " " "a" "r" "e" " " "i" "r" "r" "e"
#[23] "f" "u" "t" "a" "b" "l" "y" " " "i" "n" "t" "r" "i" "g" "u" "i" "n" "g"

length(chars1)
#[1] 40

class(chars1)
#[1] "character"
chars2 <- strsplit(rquote, split = "")
chars2
#[[1]] <- Don't forget this [[1]], it is important
# [1] "r" "'" "s" " " "i" "n" "t" "e" "r" "n" "a" "l" "s" " " "a" "r" "e" " " "i" "r" "r" "e"
#[23] "f" "u" "t" "a" "b" "l" "y" " " "i" "n" "t" "r" "i" "g" "u" "i" "n" "g"

length(chars2)
#[1] 1

class(chars2)
#[1] "list"
strsplit
返回一个列表,因此添加
[[1]]
将列表添加到字符向量。当您迭代任何对象时,您迭代的对象长度在
chars1
情况下为40,在
chars2
情况下为1

chars2 <- strsplit(rquote, split = "")
chars2
#[[1]] <- Don't forget this [[1]], it is important
# [1] "r" "'" "s" " " "i" "n" "t" "e" "r" "n" "a" "l" "s" " " "a" "r" "e" " " "i" "r" "r" "e"
#[23] "f" "u" "t" "a" "b" "l" "y" " " "i" "n" "t" "r" "i" "g" "u" "i" "n" "g"

length(chars2)
#[1] 1

class(chars2)
#[1] "list"