I am using R dplyr::mutate
to conditionally change a data frame variable value. The df_forecast is derived from a CSV file input using stringsAsFactors=F
.
The variable attribute Acres
is a string, later to be cast to a factor, which contains '10-Jan' (1/10/2019). I am attempting to mutate the value of Acres '10-Jan' to '1 to 10', but the mutate is not making any changes inside the data frame.
This same failure update issue is on the second code example for 'YearBuilt' below: trying to clean / change '15' to '2015'.
I am using R Studio (3.5).
dplyr effort explored:
I have tried equal assignment
'mutate(df_forecast$Acres = case_when...' which resulted in this error msg: 'Error: unexpected '=' in: "df_forecast %>% mutate(df_forecast$Acres ="'
I tried '==' to 'mutate(df_forecast$Acres == case_when...' which resulted with 'data.frame': 22745 obs. of 19 variables
df_forecast <- data.frame(forecast)
df_forecast %>%
mutate(df_forecast$Acres == case_when(df_forecast$Acres == "10-Jan" ~ "1 to 10")) %>%
##
str(df_forecast)
df_forecast %>%
mutate(df_forecast$YearBuilt == case_when(df_forecast$YearBuilt == "15" ~ "2015")) %>%
##
str(df_forecast)
You don't have to write df_forecast$Acres
just Acres
and specifiy what has to happen when none of the conditions apply.
data <- data.frame(Acres = c("10-Jan", "10-Jan", "anytime", "10-Jan", "10-Jan", "anytime"),
stringsAsFactors = FALSE)
> data
Acres
1 10-Jan
2 10-Jan
3 anytime
4 10-Jan
5 10-Jan
6 anytim
data %>%
mutate(Acres = case_when(Acres == "10-Jan" ~ "1 to 10",
TRUE ~ Acres)) -> data
> data
Acres
1 1 to 10
2 1 to 10
3 anytime
4 1 to 10
5 1 to 10
6 anytime
I just assigned the content of Acres
back to Acres
when Acres != "10-Jan"
, but it can be anything.
UPDATE: To make the changes permanent you also have to assign the result to your data.frame.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.