如何创建一个函数来对多个列执行操作以在R中创建新列



我正在尝试将一个简单的操作应用于数据集中的多个列。

我试着使用一个类似于在多列上应用函数中解释的函数来创建多个新列,但我一直没能得到

这是方程,其中wt是一组名为wt_jan、wt_feb。。。wt_dec


ne_maintain = 0.386*wt^0.75

我尝试过使用mutate((,但一直没能想出如何多次重复我的计算。

以下是数据集的样子:

lactation wt_jan wt_feb wt_mar wt_apr wt_may wt_jun wt_jul wt_aug wt_sep wt_oct wt_nov wt_dec
1         1  600.0  612.5  625.0  637.5  643.8  650.0  656.3  662.5  668.8  675.0  681.3  687.5
2         2  693.8  700.0  706.3  712.5  715.6  718.8  721.9  725.0  728.1  731.3  734.4  737.5
3         3  740.6  743.8  746.9  750.0  750.0  750.0  750.0  750.0  750.0  750.0  750.0  750.0
4         4  750.0  750.0  750.0  750.0  750.0  750.0  750.0  750.0  750.0  750.0  750.0  750.0
5         5  750.0  750.0  750.0  750.0  750.0  750.0  750.0  750.0  750.0  750.0  750.0  750.0
6         6  750.0  750.0  750.0  750.0  750.0  750.0  750.0  750.0  750.0  750.0  750.0  750.0

最后我想要的是一组名为ne_matenance_jan的新列。。。一直到12月。我总共需要做大约10个计算,所以希望这篇文章能解决它!

也许有一个选项是使用dplyrstringr,如下所示:

data_frame %>% 
gather(key = months, value = wt, -lactation) %>% 
select(-lactation) %>% 
filter(!is.na(wt)) %>%
group_by(months) %>% 
mutate(
months = str_replace(months, "wt", "ne_maintenance"),
wt = mean(0.386*wt^0.75)) %>% 
distinct(months, .keep_all = TRUE)

输出

months                wt
<chr>              <dbl>
1 ne_maintenance_jan  53.3
2 ne_maintenance_feb  53.5
3 ne_maintenance_mar  53.7
4 ne_maintenance_apr  53.9
5 ne_maintenance_may  54.0
6 ne_maintenance_jun  54.1
7 ne_maintenance_jul  54.2
8 ne_maintenance_aug  54.3
9 ne_maintenance_sep  54.4
10 ne_maintenance_oct  54.4
11 ne_maintenance_nov  54.5
12 ne_maintenance_dec  54.6

如果我理解正确,您希望将新计算的列追加到当前表中。您可以尝试将mutateacross一起使用,如下所示:

library(tidyverse)
# a little like your df
lactation = seq(1:6)
wt_jan <- runif(6,min=600, max=700)
wt_feb <- runif(6,min=600, max=800)
wt_mar <- runif(6,min=800, max=900)
df <- data.frame(lactation,wt_jan,wt_feb,wt_mar)

df_new<- df%>% 
mutate(across(contains("wt"), #select columns containing 'wt'
~((0.386*.x)^0.75), #using anonymized function here
.names = "{sub('wt', 'ne_maintenance', col)}")) #define the names of new columns 

最新更新