将函数应用于 data.frame 和 return data.frame 中的每个元素

apply function to every element in data.frame and return data.frame

更新:之前,我使用 paste 函数作为示例,而不是任意的 myFun 函数。这个问题稍微简单一些,因为 paste 实际上可以对向量进行运算,而 myFun 不能。

我想将我自己的函数逐元素应用于 data.frame 中的每个元素,并将修改后的 data.frame 作为 return 值。

示例:

> df <- data.frame(c(1,2,3), c(2,3,4))
> df
  c.1..2..3. c.2..3..4.
1          1          2
2          2          3
3          3          4
> df_x <- magical_apply_function(df, function(x) myFun
> df_x
  c.1..2..3. c.2..3..4.
1         myFun(1)         myFun(2)
2         myFun(2)         myFun(3)
3         myFun(3)         myFun(4)

我很困惑,无法在 Internet 上的任何地方找到此问题的答案。大多数资源都在讨论 applylapplysapply,但这些资源仅适用于 vectors/lists,并且它们仅 return 列表。

for 循环真的是唯一的方法吗?

我们可以使用 mutate_alldplyr

library(dplyr)
df %>% 
     mutate_all(funs(paste0(., "x")))

或使用 base R 中的 lapply 并将其转换为 data.frame

data.frame(lapply(df, paste0,  "x"))
df <- data.frame(c(1,2,3), c(2,3,4))
df[] <- lapply(df, function(x) paste(x,"x", sep=""))
df

df[] 保留数据框的结构。

另请参阅这些 purrr 函数

library(purrr)
modify(df,paste0,"x") # output is of the same type input, so `data.frame` here

#   c.1..2..3. c.2..3..4.
# 1         1x         2x
# 2         2x         3x
# 3         3x         4x

map_df(df,paste0,"x") # output is always tibble

# # A tibble: 3 x 2
#   c.1..2..3. c.2..3..4.
#        <chr>      <chr>
# 1         1x         2x
# 2         2x         3x
# 3         3x         4x

可以不用apply(df, c(1,2), myFun)吗?使用 c(1,2) 会将函数分别应用于数据框中的每个项目:

MARGIN a vector giving the subscripts which the function will be applied over. E.g., for a matrix 1 indicates rows, 2 indicates columns, c(1, 2) indicates rows and columns.

> temp<-data.frame(le=LETTERS[1:3], nu=20:22)
> temp
  le nu
1  A 20
2  B 21
3  C 22
> apply(temp, c(1,2), function(x) {gsub('d',x,'d1d1')})
     le     nu      
[1,] "A1A1" "201201"
[2,] "B1B1" "211211"
[3,] "C1C1" "221221"

如果按行应用该函数,则该函数未正确使用:

> apply(temp, 1, function(x) {gsub('d',x,'d1d1')})
[1] "A1A1" "B1B1" "C1C1"
Warning messages:
1: In gsub("d", x, "d1d1") :
  argument 'replacement' has length > 1 and only the first element will be used
2: In gsub("d", x, "d1d1") :
  argument 'replacement' has length > 1 and only the first element will be used
3: In gsub("d", x, "d1d1") :
  argument 'replacement' has length > 1 and only the first element will be used