【问题标题】:R dplyr mutate conditional when_case fails to update dataframeR dplyr mutate 条件 when_case 无法更新数据帧
【发布时间】:2019-08-26 00:16:42
【问题描述】:

我正在使用 R dplyr::mutate 有条件地更改数据框变量值。 df_forecast 源自使用stringsAsFactors=F 的CSV 文件输入。

变量属性Acres 是一个字符串,稍后将转换为一个因子,其中包含“10-Jan”(2019 年 1 月 10 日)。我正在尝试将 Acres '10-Jan' 的值更改为 '1 to 10',但 mutate 并没有在数据框内进行任何更改。

同样的失败更新问题出现在下面“YearBuilt”的第二个代码示例中:尝试将“15”清理/更改为“2015”。

我正在使用 R Studio (3.5)。

探索dplyr的努力:

我尝试过平等分配

'mutate(df_forecast$Acres = case_when...' 导致此错误消息:'错误:意外'=' in: “df_forecast %>% 变异(df_forecast$Acres =“'

我尝试 '==' 到 'mutate(df_forecast$Acres == case_when...' 得到 'data.frame': 22745 obs. of 19 个变量

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)

【问题讨论】:

  • 仅在case_when 之前使用单个=,因为它是一个赋值运算符mutate(df_forecast$Acres = case_when......。此外,您还需要一个 TRUE 条件。
  • 如果您可以分享一些数据,例如dput(head(&lt;YourData&gt;)) 的输出,将会很有帮助。
  • ok: c(“1 月 10 日”、“1 月 10 日”、“1 月 10 日”、“1 月 10 日”、“1 月 10 日”、“1 月 10 日”)跨度>
  • 原始CVS文件有这列数据为:“1/10/2019”
  • 检查我的答案的更新。您是否将更改分配给df_forecast-data.frame?在您对 Cettt 的评论中,它看起来不像

标签: r dataframe dplyr


【解决方案1】:

您不必写df_forecast$Acres 只需Acres 并指定在不适用任何条件时必须发生的事情。

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

我只是将Acres 的内容分配回Acres Acres != "10-Jan",但它可以是任何东西。

更新:要使更改永久生效,您还必须将结果分配给您的 data.frame。

【讨论】:

  • df_forecast %>% mutate(Acres = case_when(Acres == "10-Jan" ~ "1 to 10", TRUE ~ Acres)) > df_forecast
  • df_forecast %>% mutate(Acres = case_when(Acres == "10-Jan" ~ "1 to 10", TRUE ~ Acres)) > df_forecast$Acres
  • 我看到您在代码中对 > 数据进行分配。我尝试了相同的任务,但数据框没有明显变化
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-25
  • 1970-01-01
  • 2021-03-13
  • 1970-01-01
相关资源
最近更新 更多