+-
如同在python中一样,在for循环中追加值

我试图在R中重现以下在Python中创建的函数。

# Python 
def square_area(side):
    return side * side

results = []
for i in range(1, 10):
    x = square_area(i)
    results.append(x)
print results

结果

[1, 4, 9, 16, 25, 36, 49, 64, 81]

我在R中的尝试已经。

# R
square_area <- function(side) {
side * side
}

results=list()
for (i in 1:10){ 
x <- square_area(i)
results[i] = x 
}
print(results)

结果

[[1]]
[1] 1

[[2]]
[1] 4

[[3]]
[1] 9

[[4]]
[1] 16

[[5]]
[1] 25

[[6]]
[1] 36

[[7]]
[1] 49

[[8]]
[1] 64

[[9]]
[1] 81

[[10]]
[1] 100

我不知道这样做是否正确,但我需要将结果作为一个列表,以便稍后建立一个线图。这似乎更像是一个有键和值的python字典。如何在R中简单地追加值?

谢谢。

0
投票

我们可以直接通过做 ^ 在...上 vector

 (1:10)^2
 #[1]   1   4   9  16  25  36  49  64  81 100

如果你需要 list,只要把它用 as.list

 as.list((1:10)^2)
0
投票

Python 中的 list 和 R 中的向量是一样的,这是完全错误的。

列表可以保存许多不同种类的值,向量不能,就像矩阵一样。

在Python中,你可以做列表。

[1, [2, 3.333], "I'm a string bitch!", [1, "hollymolly"]]

但在R中,用向量是无法做到的。你可以用一个 List 来做。这就是为什么叫List的原因。

我一直在网上搜索和你一样的东西,似乎 useRs 没有必要像 Pythonistas 一样使用 Lists,最糟糕的是 useRs 把 List 和 Vector 对象的意义混淆了,好像它们是等价的 (FALSE)。

R中的向量很像Python中的np.array。这就是为什么R很酷的原因,它不需要一个包来处理矩阵。

在你的特定例子中,你可以做的事情如下 (阅读注释)。

#R
Area2 <- function(side){   #This is your function
  side^2
}

# The truth is that in your example, is enough to employ a vector and add stuff to it. 
# That's why I will make a slightly more complex code to append shit to a list and show my point
LIST = list()

for(i in 1:2){
  vect = c()
  for(j in 1:10){
    vect = c(vect, i * Area2(j))
  }
  LIST[[i]] = vect  #This is the climax of the whole story (how to append to a List)
}

print(LIST)

Outcome:

[[1]]
 [1]   1   4   9  16  25  36  49  64  81 100

[[2]]
 [1]   2   8  18  32  50  72  98 128 162 200

然后你就可以按照你的意愿使用列表中的每个值,比如你刚刚要求的绘图。

希望能帮到你。