R 计数加1和负1的简单函数
我试图在r中开发一个非常简单的函数,其思想是: 假设我有以下序列R 计数加1和负1的简单函数,r,R,我试图在r中开发一个非常简单的函数,其思想是: 假设我有以下序列“uuddudu”,其中“U”=1和“D”=-1。我想数一下:+1,+1,-1,-1,-1,+1,-1,+1。我得到的最终数字是-1 funky <- function(n, s){ current_level = 0 U = 1 D = -1 for(i in 1:n){ if(s[i] == "U"){current_level +1} if(s[i] == "D"){current_lev
“uuddudu”
,其中“U”=1
和“D”=-1
。我想数一下:+1,+1,-1,-1,-1,+1,-1,+1
。我得到的最终数字是-1
funky <- function(n, s){
current_level = 0
U = 1
D = -1
for(i in 1:n){
if(s[i] == "U"){current_level +1}
if(s[i] == "D"){current_level -1}
}
}
funky(9, UUDDDDUDU)
funky您可以使用stringr::stru count
s <- "UUDDDDUDU"
library(stringr)
str_count(s, 'U') - str_count(s, 'D')
# [1] -1
这些方法以R为基数,应该与向量一起使用
x = "UUDDDDUDU"
一,
二,
三,
只是为了好玩(和矢量化)
s这是一种利用networkite
library(reticulate)
s <- "UUDDDDUDU"
repl_python()
>>> from collections import Counter
>>> sum([a* b for a, b in zip(Counter(list(r.s)).values(), [1, -1])])
#-1
库(网状)
s>>从集合导入计数器
>>>总和([a*b代表a,b在zip中(计数器(列表(r.s)).values(),[1,-1]))
#-1
谢谢!这看起来是一个简单的解决方案。我想完成这在基地R然而。我将看看stru count
函数,看看它们在使用什么!在base R中添加了base R解决方案,请查看函数strsplit
和regexpr
(及其好友grep
和regexec
)
x = "UUDDDDUDU"
with(data.frame(t(sapply(strsplit(x, ""), table))), U - D)
#[1] -1
foo = function(p, s) {
sapply(gregexpr(p, s), function(x) sum(x > 0))
}
foo("U", x) + (-1 * foo("D", x))
#[1] -1
2 * nchar(gsub("D", "", x)) - nchar(x)
#[1] -1
s <- c("UUDDDDUDU", "UUDUU", "DDDDDUD")
sapply(parse(text=as.expression(gsub("(.)","\\11",chartr("UD","+-",s)))),eval)
[1] -1 3 -5
library(reticulate)
s <- "UUDDDDUDU"
repl_python()
>>> from collections import Counter
>>> sum([a* b for a, b in zip(Counter(list(r.s)).values(), [1, -1])])
#-1