将值附加到 R 中的空向量? [英] Append value to empty vector in R?

查看:26
本文介绍了将值附加到 R 中的空向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习 R,但我不知道如何附加到列表中.

I'm trying to learn R and I can't figure out how to append to a list.

如果这是 Python,我会...

If this were Python I would . . .

#Python
vector = []
values = ['a','b','c','d','e','f','g']

for i in range(0,len(values)):
    vector.append(values[i])

你如何在 R 中做到这一点?

How do you do this in R?

#R Programming
> vector = c()
> values = c('a','b','c','d','e','f','g')
> for (i in 1:length(values))
+ #append value[i] to empty vector

推荐答案

在for循环中追加到一个对象会导致每次迭代都复制整个对象,导致很多人说R很慢",或应避免 R 循环".

Appending to an object in a for loop causes the entire object to be copied on every iteration, which causes a lot of people to say "R is slow", or "R loops should be avoided".

正如评论中提到的 BrodieG:预先分配所需长度的向量要好得多,然后设置循环中的元素值.

As BrodieG mentioned in the comments: it is much better to pre-allocate a vector of the desired length, then set the element values in the loop.

这里有几种将值附加到向量的方法.他们都感到气馁.

Here are several ways to append values to a vector. All of them are discouraged.

# one way
for (i in 1:length(values))
  vector[i] <- values[i]
# another way
for (i in 1:length(values))
  vector <- c(vector, values[i])
# yet another way?!?
for (v in values)
  vector <- c(vector, v)
# ... more ways

help("append") 会回答你的问题并节省你写这个问题的时间(但会导致你养成坏习惯).;-)

help("append") would have answered your question and saved the time it took you to write this question (but would have caused you to develop bad habits). ;-)

注意 vector <- c() 不是空向量;它是 NULL.如果你想要一个空的字符向量,使用 vector <- character().

Note that vector <- c() isn't an empty vector; it's NULL. If you want an empty character vector, use vector <- character().

如果你绝对必须使用 for 循环,你应该在循环之前预先分配整个向量.这将比追加更大的向量快得多.

If you absolutely must use a for loop, you should pre-allocate the entire vector before the loop. This will be much faster than appending for larger vectors.

set.seed(21)
values <- sample(letters, 1e4, TRUE)
vector <- character(0)
# slow
system.time( for (i in 1:length(values)) vector[i] <- values[i] )
#   user  system elapsed 
#  0.340   0.000   0.343 
vector <- character(length(values))
# fast(er)
system.time( for (i in 1:length(values)) vector[i] <- values[i] )
#   user  system elapsed 
#  0.024   0.000   0.023 

这篇关于将值附加到 R 中的空向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆