A data.frame: 6 × 3
Id ActivityDay Calories
<dbl> <chr> <int>
1 1503960366 4/12/2016 1985
2 1503960366 4/13/2016 1797
3 1503960366 4/14/2016 1776
4 1503960366 4/15/2016 1745
5 1503960366 4/16/2016 1863
6 1503960366 4/17/2016 1728
Above is a head()
preview of the dataset, I am trying to convert column name ActivityDay into ActivityDate while converting all the column names into lower cases, following are my codes:
# calories
calories %>%
rename_with(calories, tolower) %>%
rename(activitydate=activityday)
Error: Can't rename columns that don't exist.
✖ Column `ActivityDay` doesn't exist.
Please help point out where I did wrong with the codes, thank you!
CodePudding user response:
You don't need to call calories
(your dataframe name) twice:
calories %>%
rename_with(tolower) %>%
rename(activitydate = activityday)
data
calories <- structure(list(Id = c(1503960366L, 1503960366L, 1503960366L,
1503960366L, 1503960366L, 1503960366L), ActivityDay = c("4/12/2016",
"4/13/2016", "4/14/2016", "4/15/2016", "4/16/2016", "4/17/2016"
), Calories = c(1985L, 1797L, 1776L, 1745L, 1863L, 1728L)), class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6"))
CodePudding user response:
Here is an alternative approach:
library(dplyr)
library(stringr)
calories %>%
rename_with(., ~tolower(str_replace(., "activityday", "activitydate"))))
id activitydate calories
1 1503960366 4/12/2016 1985
2 1503960366 4/13/2016 1797
3 1503960366 4/14/2016 1776
4 1503960366 4/15/2016 1745
5 1503960366 4/16/2016 1863
6 1503960366 4/17/2016 1728