Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/git/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在R中重写此列表_Python_R_List Comprehension - Fatal编程技术网

Python 在R中重写此列表

Python 在R中重写此列表,python,r,list-comprehension,Python,R,List Comprehension,不是这样的 >>> [(x*y) for (x,y) in zip(range(3), (1,11,111))] [0, 11, 222] > data.frame(0:2,c(1,11,111)) X0.2 c.1..11..111. 1 0 1 2 1 11 3 2 111 > dat

不是这样的

>>> [(x*y) for (x,y) in zip(range(3), (1,11,111))]
[0, 11, 222]                                             
> data.frame(0:2,c(1,11,111))
  X0.2 c.1..11..111.
1    0             1
2    1            11
3    2           111
> data.frame(0:2,c(1,11,111))->a
> a[1]*a[2]
  X0.2
1    0
2   11
3  222
但是像这样的

>>> [(x*y) for (x,y) in zip(range(3), (1,11,111))]
[0, 11, 222]                                             
> data.frame(0:2,c(1,11,111))
  X0.2 c.1..11..111.
1    0             1
2    1            11
3    2           111
> data.frame(0:2,c(1,11,111))->a
> a[1]*a[2]
  X0.2
1    0
2   11
3  222

你的问题我不清楚
lappy
在列表的元素上循环。因此,您的匿名函数将应用于
a
的每一列,但您的示例似乎表明您希望对这两列应用二进制函数

我猜你想要这样的东西:

lapply(a, function(x)
{   ...how can I access here the parameters of x? 
    (not using x[1] or x[2])
}

大概是一般模式吧

do.call("*",a)
# [1]   0  11 222

或者更明确地说

unlist(Map(`*`, 0:2, c(1, 11, 111)))
(我更喜欢
Map
而不是Steve的
mappy
,因为它默认情况下不简化,输入较短,并且可以很好地使用手册页上记录的其他功能,例如
Reduce
Filter
Negate


这个问题的一个早期答案,自从被删除后,就是
0:2*c(1,11,111)
,这将更加有效。

Josh的答案非常准确,但是如果你想概括一下
zip
在Python上下文中为你做的事情,看看
mapply
,它是“应用”的一次对多个“事物”进行排序,并对每个“事物”的
i
th元素应用一个函数,例如:


x1所以您想提供一个函数和一个列表,并使用模式匹配将函数应用于列表的元素?+1啊,如果我知道
zip
做了什么,它会有所帮助。OP可能正在查找
mapply
和/或
Map
。虽然在本例中,
do.call
会更快,因为二进制函数是矢量化的。+1+1+1像这样…而不是弄乱v/l/apply,
Reduce
Filter
?!?胃口…我甚至不知道地图/缩略的存在。这为非R用户提供了一个非常干净、众所周知的语法。
x1 <- 0:2
x2 <- c(1, 11, 111)
mapply(function(x, y) x*y, x1, x2)
## [1]   0  11 222
x3 <- c(10, 20, 30)
mapply(function(x, y, z) x * y + z, x1, x2, x3)
## [1]  10  31 252