R mutate 不会添加列

标签 r dplyr zoo mutated

我正在尝试使用 mutate 函数为我的数据形成三个新列。我尝试定义一些数据,但它没有改变它。我看过之前的例子,但在使用 mutate 之前似乎都使用了组函数。我认为在使用 mutate 之前我不需要创建一个组,因为它不适合我的数据。

这是我正在使用的 R 代码:


    title: "lnrmssd"
    author: "AG"
    date: '2022-03-16'
    output: pdf_document
    ---
    ```{r setup, include=FALSE}
    knitr::opts_chunk$set(echo = FALSE)
    
    
    library(tidyverse)
    library(readxl)
    library(here)
    library(knitr)
    library(caTools)
    library(httpuv)
    library(zoo)
    library(RcppRoll)
    library(dplyr)
    
    hrv <- read_excel(here("hrvdata.xlsx"))
    
    
    
    hrv <- na.omit(hrv)
    
     ### not sure if I need to define
    
    lnrmssd <- pull(hrv,3)
    HRVSD <- sd(lnrmssd, na.rm = T)
    HRVRM <- rollmean(lnrmssd,7, na.pad = T, align = 'right')
    
    ### here is where I am trying to mutate
    
    mutate("HRVSD" = sd(lnrmssd, na.rm = T)
    "HRVRM" = rollmean(lnrmssd,7, na.pad = T, align = 'right')
      upper_limit = round(HRVRM + 1.5 * HRVSD, 3),
             lower_limit = round(HRVRM - 1.5 * HRVSD, 3),
             lower_limit2 = round(HRVRM - .75 * HRVSD, 3))

这是我正在使用的数据集,它是通过excel导入的:

|date       | reading        |lnrmssd |
| --------  | -------------- |------- |
| 2022-02-17| 68.9077        |4.232768|
| 2022-02-18| 62.4076        |4.133895|
| 2022-02-19| 70.7072        |4.258547|
| 2022-02-21| 81.9841        |4.406525|
| 2022-02-22| 74.8368        |4.315310|
| 2022-02-23| 84.9140        |4.441639|
| 2022-02-24| 72.4620        |4.283062|
| 2022-02-25| 79.0891        |4.370575|
I am trying to add three columns to this table, these columns would be "upper_limit", "lower_limit", and "lower_limit2".

Any help would be much appreciated.

最佳答案

mutate 的第一个参数必须是数据集。以下参数是新的列名称,不带引号,后跟 =,然后是计算。您还需要指定此值,否则包含新列的数据集将打印到屏幕上,但不会保留在环境中。

hrv <- mutate(hrv, upper_limit = round(HRVRM + 1.5 * HRVSD, 3),
                   lower_limit = round(HRVRM - 1.5 * HRVSD, 3),
                   lower_limit2 = round(HRVRM - .75 * HRVSD, 3))

关于R mutate 不会添加列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71503442/

相关文章:

调用 Fortran 模块时 R Studio 崩溃

在 R 中递归应用 lapply

r - 如何计算多列中特定值的出现次数?

删除列中项目的百分比

r - 将 Year 列复制到 R 中的 QuarterYear

r - 为动物园对象创建滞后

c++ - 如何使用 Rcpp 将 R 函数转换为 C++ 函数?

r - 使用 dplyr 和 stringr 检测多个字符串

r - 从数据帧生成时间序列列表

R - 使用 ggplot2 在线图中绘制不同时间序列的滚动平均值