我正在做R练习:
编写一个将字符串拆分为字母并根据字母顺序返回最小和最大字母的函数。
这是向量:
cities <- c("New York", "Paris", "London", "Tokyo", "Rio de Janeiro", "Cape Town")
这是我编写的代码:
first_and_last <- function(name){
name <- gsub (" ", "", name)
letters <- strsplit(name, split = "")
c(first = min(letters), last = max(letters))
}
但是,运行它时出现错误:
first_and_last(cities)
#Error in min(letters) (from #4) : invalid 'type' (list) of argument
请让我知道代码中缺少什么?谢谢!
我假设您要按元素进行操作,即对于的每个元素cities
,请按字母顺序提取第一个和最后一个字母。这是您需要的:
first_and_last <- function(name){
name <- gsub (" ", "", name)
myName <- strsplit(name, split = "")
result <- t(sapply(myName, range)) ## use function `range`
rownames(result) <- name
colnames(result) <- c("first", "last")
return(result)
}
first_and_last(cities)
# first last
# New York "e" "Y"
# Paris "a" "s"
# London "d" "o"
# Tokyo "k" "y"
# Rio de Janeiro "a" "R"
# Cape Town "a" "w"
我用过功能range()
。这将返回min
和max
。它是R的内置实现function(x) c(min(x), max(x))
。
跟进
谢谢,问题解决了。我正在R上在线课程。在他们的解决方案中,他们使用了以下代码行。如果可能的话,请您解释一下,这行代码是什么意思。特别是,双括号部分“ [[1]]”:
letters <- strsplit(name, split = "")[[1]]
strsplit
返回列表。我们试试看:
strsplit("Bath", split = "")
#[[1]]
#[1] "B" "a" "t" "h"
如果要访问字符向量,则需要[[1]]
:
strsplit("Bath", split = "")[[1]]
#[1] "B" "a" "t" "h"
只有使用向量,您才能取min
/ max
。例如:
min(strsplit("Bath",split=""))
#Error in min(strsplit("Bath", split = "")) :
# invalid 'type' (list) of argument
min(strsplit("Bath",split="")[[1]])
#[1] "a"
我相信您看到的在线示例仅包含一个字符。如果您有矢量输入,例如:
strsplit(c("Bath", "Bristol", "Cambridge"), split = "")
#[[1]]
#[1] "B" "a" "t" "h"
#[[2]]
#[1] "B" "r" "i" "s" "t" "o" "l"
#[[3]]
#[1] "C" "a" "m" "b" "r" "i" "d" "g" "e"
并且您想要申请range
每个列表元素,sapply
将很方便:
sapply(strsplit(c("Bath", "Bristol", "Cambridge"), split = ""), range)
# [,1] [,2] [,3]
#[1,] "a" "B" "a"
#[2,] "t" "t" "r"
我first_and_last
上面的功能基于sapply
。但是,为了进行漂亮的演示,我已经对结果进行了转置并指定了行/列的名称。
天哪,我只是意识到您已经在[[]]
2天前问了一个问题:Function中的Double Bracket [[]]。那你为什么还要问我解释呢???
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句