简体   繁体   English

R dplyr mutate条件when_case无法更新数据帧

[英]R dplyr mutate conditional when_case fails to update dataframe

I am using R dplyr::mutate to conditionally change a data frame variable value. 我正在使用R dplyr::mutate有条件地更改数据帧变量值。 The df_forecast is derived from a CSV file input using stringsAsFactors=F . df_forecast源自使用stringsAsFactors=F输入的CSV文件。

The variable attribute Acres is a string, later to be cast to a factor, which contains '10-Jan' (1/10/2019). 变量属性Acres是一个字符串,稍后将转换为一个包含'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. 我正在尝试将Acres的值“ 10-Jan”更改为“ 1 to 10”,但该更改未对数据帧进行任何更改。

This same failure update issue is on the second code example for 'YearBuilt' below: trying to clean / change '15' to '2015'. 下面的“ YearBuilt”的第二个代码示例上也存在同样的故障更新问题:尝试将“ 15”清除/更改为“ 2015”。

I am using R Studio (3.5). 我正在使用R Studio(3.5)。

dplyr effort explored: dplyr的努力探索:

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 ="' 'mutate(df_forecast $ Acres = case_when ...'),导致此错误消息:'错误:意外'='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 我尝试'=='进行'mutate(df_forecast $ Acres == case_when ...',这导致了'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. 你不必写df_forecast$Acres只是Acres和specifiy什么也没有时的条件适用于发生。

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. Acres != "10-Jan" ,我只是将Acres的内容分配回了Acres ,但这可以是任何东西。

UPDATE: To make the changes permanent you also have to assign the result to your data.frame. 更新:要使更改永久生效,您还必须将结果分配给data.frame。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM