选定列的mutate_each函数

3

我有一个关于使用mutate_each在我的数据框中应用function的问题。

我有一个可以计算两个波形y1y2之间相位差的函数。我想将此函数应用于我的数据并创建一个名为phase的新列,但是我得到了一个错误,说其中一个参数y2丢失,尽管我已经将它们放在了我的function中。

也许我不擅长编写函数:)

这里是一个可重现的示例:

library(dplyr)
library(psd) # Loaded psd (1.0.1) -- Adaptive multitaper spectrum estimation

time <- seq(1,30)
y1 <- sort(runif(30,-0.014,0.014),decreasing=TRUE)
y2 <- sort(runif(30,-0.012,0.012),decreasing=TRUE)
df <- data.frame(y1,y2,time)
#calculation phase difference between two waves y1 and y2  

phase_diff <- function(y1,y2,time){
  out1=pspectrum(y1*(-1),x.frqsamp = 0.1);
  out2=pspectrum(y2*(-1),x.frqsamp = 0.1);
  f1 = out1$freq[which.min(out1$spec)];
  f2 <- out2$freq[which.min(out2$spec)];
  fit1 <- lm(y1 ~ sin(2*pi*f1*time)+cos(2*pi*f1*time));
  fit2 <- lm(y2 ~ sin(2*pi*f2*time)+cos(2*pi*f2*time));
  a1 <- fit1$coefficients[2];
  b1 <- fit1$coefficients[3];
  ph1 <- atan(b1/a1);
  a2 <- fit2$coefficients[2];
  b2 <- fit2$coefficients[3];
  ph2 <- atan(b2/a2);
  phase_difference <- as.numeric((ph2-ph1)/pi);
  return(phase_difference)
}

dff <- df%>%
mutate_each(funs(phase_diff),phase=c(y1,y2,time))

Stage  0 est. (pilot) 
    environment  ** .psdEnv **  refreshed
    detrending (and demeaning)
Stage  1 est. (Ave. S.V.R. -10.9 dB) 
Stage  2 est. (Ave. S.V.R. -8.3 dB) 
Stage  3 est. (Ave. S.V.R. -8.3 dB) 
Stage  4 est. (Ave. S.V.R. -8.3 dB) 
Stage  5 est. (Ave. S.V.R. -8.3 dB) 
Normalized  single-sided  psd estimates ( psd ) for sampling-freq.  0.1
Error: argument "y2" is missing, with no default

你的初始数据集只有三列'y1'、'y2'和'time',这些是'phase_diff'函数的参数。我不明白为什么要使用'mutate_each'。简单地使用'phase_diff(df$y1, df$y2, df$time)'应该会返回输出结果。'mutate_each'是用于应用于每一列的,我在这里看不到它有用(除非我弄错了)。 - akrun
@akrun 谢谢您的询问。在我的真实数据的 dplyr 链中,我还有其他事情要做。因此,我想坚持使用 mutate_each :) - Alexander
请检查我发布的解决方案。如果您想在dplyr链中执行其他操作,可以使用mutate(根据所示示例)。 - akrun
@akrun 好的,我刚看到了。谢谢你。但是为什么 mutate_each 不起作用呢? - Alexander
1
它将“phase_diff”应用于第一列“y1”,然后应用于“y2”和“time”。但是,对于每个列,都没有相应的输入变量(因为该函数需要3个变量)。 - akrun
@akrun 哦,我明白了。向你致敬,老兄。永远支持你 ;) - Alexander
1个回答

2

由于我们需要创建一个新列,而函数phase_diff使用输入数据集中的所有列作为参数,因此操作者可能需要使用mutate而不是mutate_eachmutate_each用于应用于数据集中的每个列。

res <- df %>%
          mutate(phase = phase_diff(y1, y2, time))
head(res,2)
#         y1          y2 time      phase
# 1 0.01398857 0.010296090    1 -0.1349023
# 2 0.01334217 0.009990988    2 -0.1349023

上述操作可以使用 base R 进行。
phase_diff(df$y1, df$y2, df$time)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接