【问题标题】:select mutate column in data frame created 1 field 2 variable data.frame在创建的数据框中选择变异列 1 字段 2 变量 data.frame
【发布时间】:2020-06-20 23:03:26
【问题描述】:

问题背景:数据框的结构如下。问题是我需要一个新列,例如 status_rank,它不是 2 个变量的 data.frame。然后需要使用基于条件的另一个变量的值来更新 status_rank。

[错字:ifelse是我用的]

使用 target.market_b/_g(“坏”、“好”值)进行条件测试。 'status' 有这些以及更多应该被忽略的内容(不是 == target.market_b/_g)。

ifelse(status %in% target.marker_b, "Bad",
       ifelse(status %in% target_g, "Good", "N/A")

df$status : 字符 df$status_rank : 2 个变量的“data.frame” .. $status 字符“...” .. $status_rank chr "Bad" "Good" "N/A"

我使用 dplyr mutate 创建了一个新字段,现在我知道它会改变列“status_rank”。我现在看到 dplyr mutate 不是正确的解决方案。

df$status_rank <- df %>% 
  select(status, status_rank) %>%
     mutate(status_rank = ifelse(status %in% target.marker_b, "Bad",
       ifelse(status %in% target_g, "Good", "N/A")))

发布新列创建与

df["status_rank"] <- "N/A"

然后 mutate 对“status_rank”进行操作并将其变异为 2 个观察值。需要一种更好的方法来创建新列并应用 ifelse(status %in% target.marker_b, "Bad", ifelse(status %in% target_g, "Good", "N/A")。寻找建议。

数据:dput(df$status)

"Current", "Fully Paid", "Current", "Fully Paid", "Charged Off", "Current", "Current", "Fully Paid", "Current", "Fully Paid", "Charged Off", "Late (31-120 days)", "Current", "Fully Paid", "Current", "Fully Paid", "Charged Off", "Current", "Current", "Fully Paid", "Late (31-120 days)", "Fully Paid", "Charged Off", "Current"

【问题讨论】:

  • (1) elseif 不存在,但您可以 ifelse(cond1, yes1, ifelse(cond2, yes2, no))。 (2) 样本数据会很好,否则我们只是在黑暗中刺伤。
  • 刚刚添加了一个 dput() 示例数据
  • user1857373,你需要记住我们没有数据。您提供的内容为我们提供了足够的一列(也许对于框架,因为不需要其他列),但是......您的其他两个变量 target.marker_btarget_g 呢?

标签: r dataframe filter dplyr


【解决方案1】:

如果没有可重现的示例,您会有点难以理解您在说什么,但是您可能会对 dplyr 的 case_when 函数感兴趣:

# Untested code (as no sample data was given)

library(dplyr)

df %>% 
  mutate(status_rank = case_when(
    status %in% target.marker_b ~ "Bad",
    status %in% target_g ~ "Good",
    TRUE ~ "N/A" # Default condition to catch other cases
  ))

如果您想要一个NA 值而不是字符“N/A”,那么您不需要默认条件。不满足任何条件的行将被赋予值NA_character_

df %>% 
  mutate(status_rank = case_when(
    status %in% target.marker_b ~ "Bad",
    status %in% target_g ~ "Good"
  ))

【讨论】:

  • "N/A" 是问题所表明的,所以我两个都去了。感谢@r2evans 的帮助
  • 如何在不变异创建 2 个变量的情况下完成此操作?
  • user1857373,你是什么意思? mutate(status_rank=case_when(...)) 正在创建一个变量。
  • 我不确定创建两个变量是什么意思。 mutate 在这种情况下只会创建一个变量。
  • 你需要学习如何使用dplyrdf %&gt;% select(...) %&gt;% mutate(...) 的返回值是一个frame,而不是一个列,所以不要将它分配给df$status_rank。只需将其重新分配给df
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-02-13
  • 1970-01-01
  • 2013-11-16
  • 1970-01-01
  • 1970-01-01
  • 2013-10-14
  • 1970-01-01
相关资源
最近更新 更多