【问题标题】:Mutate with ifelse in r在 r 中使用 ifelse 进行变异
【发布时间】:2020-03-21 17:23:46
【问题描述】:

我正在处理一个数据框(尺寸:10,155 x 33)。数据框的几行和几列是

  rg[1:3, 1:4]

  REF_NO children age_band  status
1   2148        1    45-50 Partner
2   8099        1    61-65 Partner
3   6611        3    31-35 Partner


> table(rg_age_band)

  18-21   22-25   26-30   31-35   36-40   41-45   45-50   51-55 
     63     456     927    1061    1134    1112    1359    1052 
  55-60   61-65   65-70     71+ Unknown 
   1047     881     598     410      55 

对于变量age_band,我想使用tidyverse函数separate(), mutate() & chaining operator进行以下嵌套操作:

  1. 将 age_band 分成两列 a1 和 a2
  2. 将 a1 列中的“71+”替换为“71”
  3. 将 a1 和 a2 列转换为数值类
  4. 创建一个列“年龄”,它是 a1 和 a2 列的平均值
  5. 删除列 a1 和 a2

我正在使用以下代码:

library(tidyr); library(dplyr)

rg1=rg %>% 
  separate(age_band, into = c("a1", "a2"), sep="-") %>% 
  mutate(a1 = as.numeric(ifelse(rg$a1=="71+", 71, rg$a1)),
         a2 = as.numeric(a2),
         age = 0.5*(a1+a2)) %>% 
  select(-a1-a2)

Error: Column `a1` must be length 10155 (the number of rows) or one, not 0 

错误:列 a1 的长度必须为 10155(行数)或 1,而不是 0 请建议可以做什么。 当我在 ifelse 语句中运行没有“$”的代码时,我得到一个错误object 'a1' not found,而通常,我们在使用链接运算符和变异时不需要'$'。 对Similar question 的讨论无法提供任何有用的解决方案。 我尝试了代码片段,问题出在

mutate(a1 = as.numeric(ifelse(rg$a1=="71+", 71, rg$a1))

还有

#is producing warning 
Expected 2 pieces. Missing pieces filled with `NA` in 465 rows```



编辑:附加sample data

【问题讨论】:

  • 在你调用mutate的时候,a1还没有被创建,所以rg$a1是NULL或者长度为零;因此 ifelse 的长度为零。
  • 它是由tidyr的separate()函数创建的。
  • 对我来说,您似乎不需要rg$a1,只需尝试:as.numeric(ifelse(rg$a1=="71+", 71, a1))。可能还有其他问题..

标签: r if-statement dplyr


【解决方案1】:

以下代码不会产生任何错误:

rg <- data.frame(REF_NO = c(2148, 8099, 6611), children = c(1,1,3), age_band = c("45-50", "61-65", "71+"))

rg %>% 
  tidyr::separate(age_band, into = c("a1", "a2"), sep="-") %>% 
  mutate(a1 = as.numeric(ifelse(a1=="71+", 71, a1)),
         a2 = as.numeric(a2),
         age = 0.5*(a1+a2)) %>% 
  select(-a1, -a2)

【讨论】:

  • 它也对我有用。但是,当我一点一点地运行我的代码[带有或不带有'$'] [例如,每次 mutate 中的一个语句] 时,代码的各个部分都在工作。但是当一起运行整个块时,我遇到了上面提到的错误。奇怪的行为,我无法弄清楚。
  • 那么您的数据中可能还有其他问题正在造成问题。您能否尝试一次运行一千行:rg[1:1000, ] %&gt;% ... 并尝试缩小范围?也许在您的问题中包含更大的数据摘录?
  • 我附上了一个示例数据。
  • 使用这个示例,我仍然无法重现任何错误,使用我上面提供的代码。警告用于解释数据中引入的 NA:1: Expected 2 pieces. Missing pieces filled with NA`,共 237 行 [9, 73, 98, 115, 164, 165, 181, 202, 233, 250, 257, 286, 311, 323, 341, 368, 372, 381, 383, 400, ...].` 是为了警告你,对于“71+”,a2 变量是 NA。
  • 2: NAs introduced by coercion 是在 a1 上执行的 as.numeric 操作的警告(如果它是“未知”)
猜你喜欢
  • 2021-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多