在 R 中压缩或枚举? [英] Zip or enumerate in R?

查看:13
本文介绍了在 R 中压缩或枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这些 Python 列表推导式的 R 等价物是什么:

[(i,j) for i,j in zip(index, Values)][(i,j) for i,j in enumerate(Values)][(i,j) for i,j in enumerate(range(10,20))] %MWE,索引或枚举到%跟上指数,可能有%be 一些参数来查找这个

输出示例

<预><代码>>>>[(i,j) for i,j in enumerate(range(10,20))][(0, 10), (1, 11), (2, 12), (3, 13), (4, 14), (5, 15), (6, 16), (7, 17), (8, 18), (9, 19)]

我之前用 R 中的一些技巧解决了这个问题,但不再记得了,第一个想法是 itertools -pkg 但我希望找到一种更惯用的做事方式.

解决方案

python的答案enumerate:

在 R 中,一个列表是有序的(参见这个答案).因此,您只需要索引键(使用 names()[i])或值(使用 [[i]]).

使用seq_along(或者可以做for(i in 1:length(mylist)){...}):

>mylist <- list('a'=10,'b'=20,'c'=30)>for (i in seq_along(mylist)){+ 打印(粘贴(我,名字(我的名单)[我],我的名单[[我]]))+ }[1] "1 到 10"[1] "2 b 20"[1] "3 c 30"

python的答案zip:

请参阅上述答案之一以模拟元组列表.我更喜欢使用数据框,如 BondedDust 的回答所示:

>x <- 1:3>y <- 4:6>数据框(x=x,y=y)xy1 1 42 2 53 3 6

What are the R equivalents for these Python list comprehensions:

[(i,j) for i,j in zip(index, Values)]
[(i,j) for i,j in enumerate(Values)]
[(i,j) for i,j in enumerate(range(10,20))]   %MWE, indexing or enumerating to 
                                            %keep up with the index, there may 
                                            %be some parameter to look this up

Example with Output

>>> [(i,j) for i,j in enumerate(range(10,20))]
[(0, 10), (1, 11), (2, 12), (3, 13), (4, 14), (5, 15), (6, 16), (7, 17), (8, 18), (9, 19)]

I have solved this problem earlier with some trick in R but cannot remember anymore, the first idea was itertools -pkg but I am hoping to find a more idiomatic way of doing things.

解决方案

Answer for python enumerate:

In R, a list is ordered (see this answer). Thus, all you need is to index either keys (using names()[i]) or values (using [[i]]).

Using seq_along (alternatively can do for(i in 1:length(mylist)){...}):

> mylist <- list('a'=10,'b'=20,'c'=30)
> for (i in seq_along(mylist)){
+   print(paste(i,names(mylist)[i],mylist[[i]]))
+ }
[1] "1 a 10"
[1] "2 b 20"
[1] "3 c 30"

Answer for python zip:

See one of the above answers to mimic the list of tuples. My preference is towards a data frame as shown in BondedDust's answer:

> x <- 1:3
> y <- 4:6
> data.frame(x=x, y=y)
  x y
1 1 4
2 2 5
3 3 6

这篇关于在 R 中压缩或枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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