我倾向于使用 dplyr 的 mutate_each 和 summarise_each 函数将相同的函数应用于多个列。以下是您可以使用自定义“交换”函数以提高可读性的方法:
library(dplyr)
定义一个函数:
swap <- function(x) c(last(x), head(x, -1L))
现在您可以在“mutate_each”中使用此自定义函数并指定要将函数应用于的列:
mutate_each(df, funs(swap), col3, col4)
# col1 col2 col3 col4
#1 a b k l
#2 e f c d
#3 i j g h
如果您更喜欢 base R,您可以类似地执行此操作,使用稍微修改的函数“swap2”和“lapply”将函数应用于多个列:
# define the function:
swap2 <- function(x) c(tail(x, 1L), head(x, -1L))
# define the columns you want to apply the function to:
cols <- c("col3", "col4")
# Finally, lapply over the data:
df[cols] <- lapply(df[cols], swap2)
数据:
> dput(df)
structure(list(col1 = c("a", "e", "i"), col2 = c("b", "f", "j"
), col3 = c("c", "g", "k"), col4 = c("d", "h", "l")), .Names = c("col1",
"col2", "col3", "col4"), class = "data.frame", row.names = c(NA,
-3L))