我想编写一个代码来计算和求和任何正数和负数系列。
数字为正数或负数(无零)。
我用for循环编写了代码。有没有创意的替代品?
set.seed(100)
x <- round(rnorm(20, sd = 0.02), 3)
Run Code Online (Sandbox Code Playgroud)
x = [-0.01, 0.003, -0.002, 0.018, 0.002, 0.006, -0.012, 0.014, -0.017, -0.007,
0.002, 0.002, -0.004, 0.015, 0.002, -0.001, -0.008, 0.01, -0.018, 0.046]
Run Code Online (Sandbox Code Playgroud)
sign_indicator <- ifelse(x > 0, 1,-1)
number_of_sequence <- rep(NA, 20)
n <- 1
for (i in 2:20) {
if (sign_indicator[i] == sign_indicator[i - 1]) {
n <- n + 1
} else{
n <- 1
}
number_of_sequence[i] <- n
} …Run Code Online (Sandbox Code Playgroud) 我想回答一个关于plotmath的问题但是我没有得到我想要的替代输出.我想要的输出:plotmath
我得到了什么:substitute
text<-'paste(italic(yes),"why not?")'
text
[1] "paste(italic(yes),\"why not?\")"
noqoute_text<-noquote(text)
noqoute_text
[1] paste(italic(yes),"why not?")
sub<-substitute(paste("Hi",noqoute_text),
env=list(noqoute_text=noqoute_text))
sub
paste("Hi", "paste(italic(yes),\"why not?\")")
Run Code Online (Sandbox Code Playgroud) 我一直在与H2O中Rmarkdown,当我想保存在一个文本文件的输出,刚才保存的第一部分(页),但是,它是在控制台确定
我使用以下代码:
fileConn<-file(".\\h2o.randomForest\\output.txt")
writeLines(capture.output(summary(rf1)), fileConn)
close(fileConn)
Run Code Online (Sandbox Code Playgroud)
如何将所有输出保存到文本文件?
您可以在Rmarkdown中尝试以下代码
library(h2o)
h2o.init()
# import the iris dataset:
# this dataset is used to classify the type of iris plant
# the original dataset can be found at https://archive.ics.uci.edu/ml/datasets/Iris
iris <-h2o.importFile("http://h2o-public-test-data.s3.amazonaws.com/smalldata/iris/iris_wheader.csv")
# convert response column to a factor
iris['class'] <-as.factor(iris['class'])
# set the predictor names
predictors <-colnames(iris)[-length(iris)]
# split into train and validation
iris_splits <- h2o.splitFrame(data = iris, ratios = .8, seed = 1234)
train <- iris_splits[[1]]
valid …Run Code Online (Sandbox Code Playgroud) 我回顾了python问题如何从list中删除每次出现的sub-list。现在,我想知道R中有多少种创意方式。
例如,sub_list从中删除所有出现的方式main_list。
main_list = c(2, 1, 2, 3, 1, 2, 4, 2, 2 ,1)
sub_list = c(1,2)
Run Code Online (Sandbox Code Playgroud)
预期结果: 2 3 4 2 2 1
我的建议:
a<-c()
for(i in 1:(length(main_list)-1)){
if (all(main_list[c(i,i+1)]==sub_list))
{a<-c(a,c(i,i+1))}
}
main_list[-a]
[1] 2 3 4 2 2 1
Run Code Online (Sandbox Code Playgroud)
2
as.numeric(unlist(strsplit(gsub("(12)","",paste0(main_list,collapse = "")),split = "")))
Run Code Online (Sandbox Code Playgroud)
哦,真的很危险。我们试试吧:
main_list = c(2, 1, 2, 3, 12, 1, 2, 4, 2, 2, 1)
as.numeric(unlist(strsplit(gsub("(12)","",paste0(main_list,collapse = "")),split = "")))
[1] 2 3 4 2 2 1
####However …Run Code Online (Sandbox Code Playgroud) 我想按第二行对矩阵或数据框进行排序。我找到办法。
tt<-c(3,2,3,5,3,5,5,4,3,1,5,2,1,5,4,1,3,5,3,3)
ff<-matrix(tt,nrow=5)
gg<-t(ff)
nn<-gg[order(gg[,2],decreasing = T),]
ff<-t(nn)
ff
Run Code Online (Sandbox Code Playgroud)
有其他选择或建议吗?