簡體   English   中英

將函數應用於數據框列表中的相應元素

[英]Apply function to corresponding elements in list of data frames

我在 R 中有一個數據框列表。列表中的所有數據框的大小都相同。 然而,元素可以是不同的類型。 例如,

在此處輸入圖片說明

我想將一個函數應用於數據框的相應元素。 例如,我想使用粘貼功能來生成一個數據框如

"1a" "2b" "3c"

"4d" "5e" "6f"

在 R 中是否有一種直接的方法可以做到這一點。我知道可以使用 Reduce 函數將函數應用於列表中數據幀的相應元素。 但是在這種情況下使用 Reduce 函數似乎並沒有達到預期的效果。

Reduce(paste,l)

產生:

"c(1, 4) c(\"a\", \"d\")" "c(2, 5) c(\"b\", \"e\")" "c(3, 6) c(\"c\", \"f\")"

想知道我是否可以在不編寫凌亂的 for 循環的情況下做到這一點。 任何幫助表示贊賞!

而不是Reduce ,使用Map

 # not quite the same as your data
 l <- list(data.frame(matrix(1:6,ncol=3)),
           data.frame(matrix(letters[1:6],ncol=3), stringsAsFactors=FALSE))
 # this returns a list
 LL <- do.call(Map, c(list(f=paste0),l))
 #
 as.data.frame(LL)
 #  X1 X2 X3
 # 1 1a 3c 5e
 # 2 2b 4d 6f

為了進一步解釋@mnel 的出色答案,請考慮對兩個向量的相應元素求和的簡單示例:

Map(sum,1:3,4:6)

[[1]]
[1] 5  # sum(1,4)

[[2]]
[1] 7  # sum(2,5)

[[3]]
[1] 9  # sum(3,6)

Map(sum,list(1:3,4:6))

[[1]]
[1] 6  # sum(1:3)

[[2]]
[1] 15 # sum(4:6)

通過添加第二個列表,可能會更明顯地說明為什么第二個是這種情況,例如:

Map(sum,list(1:3,4:6),list(0,0))

[[1]]
[1] 6  # sum(1:3,0)

[[2]]
[1] 15 # sum(4:6,0)

現在,下一個更棘手。 正如幫助頁面?do.call所述:

 ‘do.call’ constructs and executes a function call from a name or a
 function and a list of arguments to be passed to it.

所以,這樣做:

do.call(Map,c(sum,list(1:3,4:6)))

使用列表c(sum,list(1:3,4:6))的輸入調用Map ,如下所示:

[[1]] # first argument to Map
function (..., na.rm = FALSE)  .Primitive("sum") # the 'sum' function

[[2]] # second argument to Map
[1] 1 2 3

[[3]] # third argument to Map
[1] 4 5 6

...因此相當於:

Map(sum, 1:3, 4:6)

看起來很熟悉! 它相當於這個答案頂部的第一個例子。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM