Link to home
Start Free TrialLog in
Avatar of Bryan Schmidt
Bryan SchmidtFlag for United States of America

asked on

How to rename a column in R

I need to rename the column labelled "Amount" with "Kurtosis" in a dataframe in R and cannot find the correct way to do this. I have tried the following.

library(tidyverse)
library(ggplot2)
library(scales)
library(readr)
library(moments) #needed to calculate skewness and kurtosis

xmas_df <- read.csv("C:/Excel/For R/tblMainXMasFund.csv", header = TRUE, stringsAsFactor = FALSE)
xmasTotals_df_Kurtosis <- xmas_df %>%
  dplyr::rename(Kurtosis=Amount) %>%
  group_by(Year, YTD_Range) %>%
  summarise(Amount = kurtosis(Amount))


The above produces the following error: 

Error in `summarise()`:
! Problem while computing `Amount = kurtosis(Amount)`.
i The error occurred in group 1: Year = 2018, YTD_Range =
  "1/1/2018 to 12/31/2018".
Caused by error in `kurtosis()`:
! object 'Amount' not found


If I change dplyr::rename(Kurtosis=Amount) %>% to dplyr::rename(Amount=Kurtosis) %>% I get: ! Can't rename columns that don't exist.
x Column `Kurtosis` doesn't exist.


Any suggestions on how to modify the above would be appreciated.

Avatar of Molly Fagan
Molly Fagan
Flag of United States of America image

You're not using the correct "piping" for the rename and it needs to be done separately from the summarise.

xmasTotals_df_Kurtosis %<>% rename(Amount = Kurtosis)

Open in new window

Do that and the Amount column will exist and you'll be able to use it.
Avatar of Bryan Schmidt

ASKER

I made the change you describe but get: Error in xmas_df %>% group_by(Year, YTD_Range) %>% summarise(Amount = kurtosis(Amount)) %>%  :
  could not find function "%<>%"

Here is my code:
xmas_df <- read.csv("C:/Excel/For R/tblMainXMasFund.csv", header = TRUE, stringsAsFactor = FALSE)
xmasTotals_df_Kurtosis <- xmas_df %>%
  group_by(Year, YTD_Range) %>%
  summarise(Amount = kurtosis(Amount)) %>%
  xmasTotals_df_Kurtosis %<>% rename (Amount = Kurtosis)

What modifications should I make? Do I need to add a library that reads the function %<>%?
ASKER CERTIFIED SOLUTION
Avatar of Molly Fagan
Molly Fagan
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I added the magrittr library but got the following message: Error in `stop_subscript()`:
! Can't rename columns that don't exist.
x Column `Kurtosis` doesn't exist.

I then reversed the order of Amount and Kurtosis in the last line to read xmasTotals_df_Kurtosis %<>% rename (Kurtosis = Amount) and it worked!

Thank you Molly! Your time and advice are greatly appreciated!