选择“数据框创建1字段2变量data.frame”中的“变异列”

选择“数据框创建1字段2变量data.frame”中的“变异列”,r,dataframe,filter,mutate,R,Dataframe,Filter,Mutate,问题背景:数据帧的结构如下。问题是我需要一个新列,例如status_rank,它不是一个包含两个变量的数据框架。然后需要使用基于另一个条件变量的值更新status_rank [输入错误:ifelse是我使用的] 使用target.market\u b//u g(“坏”、“好”值)进行有条件尝试。'“状态”中有这些加上更多应该忽略的内容(not==target.market\u b/\u g) df$状态:chr df$status_秩:2个变量的“data.frame” .. $状态chr“…”

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

[输入错误:ifelse是我使用的]

使用target.market\u b//u g(“坏”、“好”值)进行有条件尝试。'“状态”中有这些加上更多应该忽略的内容(not==target.market\u b/\u g)

df$状态:chr df$status_秩:2个变量的“data.frame” .. $状态chr“…” .. $状态等级chr“坏”“好”“不适用”

我使用dplyr mutate创建了一个新字段,现在我知道它对“status\u rank”列进行了修改。我现在知道dplyr突变不是正确的解决方案

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")))


如果没有一个可复制的示例,就有点难以理解您所说的内容,但是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\u character\u

i、 e


(1)
elseif
不存在,但您可以
ifelse(cond1,yes1,ifelse(cond2,yes2,no))
。(2) 示例数据会很好,否则我们只是在暗中摸索。只需添加一个dput()示例datauser1857373,您需要记住我们没有数据。您提供的内容为我们提供了足够的一个列(也许是框架,因为不需要其他列),但是。。。你的另外两个变量
target.marker_b
target_g
?“N/A”是问题所指示的,所以我两个都用了。感谢@r2evanshow的帮助,我能在不创建两个变量的情况下完成这个任务吗?user1857373,你是什么意思
mutate(status\u rank=case\u when(…)
只创建了一个变量。我不确定创建两个变量是什么意思
mutate
在这种情况下只会创建一个变量。您需要学习如何使用
dplyr
df%>%select(…)%%>%mutate(…)
的返回值是一个框架,而不是一个列,因此不要将其分配给
df$status\u rank
。只需将其重新分配到
df
df["status_rank"] <- "N/A"
"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"
# 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
  ))
df %>% 
  mutate(status_rank = case_when(
    status %in% target.marker_b ~ "Bad",
    status %in% target_g ~ "Good"
  ))