您也可以直接对dataframe执行相同的操作:
df[paste0(names(df), 2)] <- df^2
df
# dog_c cat_c cheese_c hat_c dog_c2 cat_c2 cheese_c2 hat_c2
#1 3 4 3 2 9 16 9 4
#2 3 1 2 5 9 1 4 25
#3 5 2 1 4 25 4 1 16
如果你想这样做
dplyr
mutate_all
library(dplyr)
df %>% mutate_all(list(`2` = ~. ^2))
如果只对选定列执行此操作,则可以执行以下操作:
cols <- c('dog_c','cat_c') #Use regex if there are lot of columns.
df[paste0(cols, 2)] <- df[cols]^2
# dog_c cat_c cheese_c hat_c dog_c2 cat_c2
#1 3 4 3 2 9 16
#2 3 1 2 5 9 1
#3 5 2 1 4 25 4
mutate_at
具有
dplyr公司
df %>% mutate_at(cols, list(`2` = ~.^2))
df <- structure(list(dog_c = c(3L, 3L, 5L), cat_c = c(4L, 1L, 2L),
cheese_c = 3:1, hat_c = c(2L, 5L, 4L)), class = "data.frame",
row.names = c(NA, -3L))