0
votes

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)
1
Only use single = before case_when as it is an assignment operator mutate(df_forecast$Acres = case_when....... Also you would also need a TRUE condition.Ronak Shah
It would be helpful if you could share some of your data, for example the output of dput(head(<YourData>)).A. Stam
ok: c("10-Jan", "10-Jan", "10-Jan", "10-Jan", "10-Jan", "10-Jan")user1857373
the original CVS file has this column data as: "1/10/2019"user1857373
check the update to my answer. Do you assign your changes to your df_forecast-data.frame? In your comment to Cettt it didn't look like itHumpelstielzchen

1 Answers

1
votes

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.