I am trying to use the mutate function to form three new columns to my data. I have tried defining some of the data and it has not changed it. I have looked at previous examples but all seem to use a group function before using mutate. I think I do not need to create a group before using mutate as it would not fit with my data.
Here is the R code I am using:
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))
Here is the data set I am using, it is imported via 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.
CodePudding user response:
The first argument of mutate
must be the dataset. The following arguments are the new column names, without quotation marks, followed by an =
and then the calculation. You also need to assign this otherwise the dataset with the new columns will be printed to screen but won't be kept in the environment.
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))
CodePudding user response:
hrv <- read_excel(here("hrvdata.xlsx"))
hrv <- na.omit(hrv)
hrv <- hrv %>% 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))