R把循环放入向量中

时间:2017-10-31 15:42:46

标签: r for-loop vector

我想将以下for循环的输出放入单个向量中。

test=c("A","B","C","D")
for(i in 1:3)
 {e=runif(1,5,10);
  f=round(e);
  g=sample(test,f,TRUE);
  h=paste(g,collapse = "");
    print(h)}

输出:

[1] "BDCCABD"
[1] "DDBAADBBAA"
[1] "DACCAB"

我想得到一个像:

这样的矢量
i=c("BDCCABD","DDBAADBBAA","DACCAB")

感谢您的帮助

6 个答案:

答案 0 :(得分:1)

只需稍微修改一下你的代码即可。

set.seed(8632)    # make the results reproducible

i <- sapply(1:3, function(x){
    e = runif(1, 5, 10)
    f = round(e)
    g = sample(test, f, TRUE)
    h = paste(g, collapse = "")
    print(h)
    h
})

i
#[1] "CACDAABCC" "ADDAACA"   "ACCDAACAB"

你真的需要print(h)吗?

修改
我刚刚测试了它,以下简化给出了完全相同的结果。

set.seed(8632)    # make the results reproducible

j <- sapply(1:3, function(x){
    f <- sample(5:10, 1)        # this is equivalent to your original code
    g = sample(test, f, TRUE)
    h = paste(g, collapse = "")
    print(h)
    h
})

j
#[1] "CACDAABCC" "ADDAACA"   "ACCDAACAB"

identical(i, j)
#[1] TRUE

答案 1 :(得分:0)

我认为是这样的:

test=c("A","B","C","D")
h_final<-0
for(i in 1:3){e=runif(1,5,10);
f=round(e);
g=sample(test,f,TRUE);
h=paste(g,collapse = "");
h_final[i]<-h
if(i==3){print(h_final)}
}

答案 2 :(得分:0)

这样的事情?

j <- character()

test = c("A", "B", "C", "D")
for (i in 1:3) {
  e = runif(1, 5, 10)
  f = round(e)
  g = sample(test, f, TRUE)
  h = paste(g, collapse = "")

  j <- c(j, h)
}

print(j)

> print(j)
[1] "DDDBADBCD" "ABBCBCC"   "BBCAA"

编辑:更简单

test = c("A", "B", "C", "D")
for (i in 1:3) {
  e = runif(1, 5, 10)
  f = round(e)
  g = sample(test, f, TRUE)
  h[i] = paste(g, collapse = "")
  }

> print(h)
[1] "DBDADDD"  "AABDA"    "CDBDDABC"

答案 3 :(得分:0)

你应该看看vectors in R

您需要初始化一个空向量,让我们称之为test_vector

test_vector = c()
test=c("A","B","C","D")

for(i in 1:3)
    {e=runif(1,5,10);
    f=round(e);
    g=sample(test,f,TRUE);
    h=paste(g,collapse = "");
    print(h)
    test_vector <- c(test_vector,h)
    }

请注意,您可以直接将函数应用于test向量,而无需使用for循环。

答案 4 :(得分:0)

你提到了vector,然后让我们使用vector

V=vector()
test=c("A","B","C","D")
for(i in 1:3)
{e=runif(1,5,10);
f=round(e);
g=sample(test,f,TRUE);
h=paste(g,collapse = "");
V[i]=h}

V
[1] "BCCAD"     "CCDCACBAD" "ADCDBCBCC"
V[1]
[1] "BCCAD"

答案 5 :(得分:0)

不是最优雅的方式,特别是如果你有很多迭代但它有效:

test=c("A","B","C","D")
k = NA
for(i in 1:3)
{e=runif(1,5,10)
f=round(e)
g=sample(test,f,TRUE)
h=paste(g,collapse = "")
k = append(k,h)
print(h)}

k <- na.omit(k)