【发布时间】:2018-12-22 03:42:37
【问题描述】:
我在尝试通过调用 filter() 来替换数据帧中的 NA 时遇到了麻烦。
tib <- as_tibble(data.frame("Group"= c("A", "A", "A", "A", "A", "A", "B", "B", "B", "B", "B", "B"), "Color" = c("Red", "Red", "Red", "Blue", "Blue", "Blue", "Red", "Red", "Red", "Blue", "Blue", "Blue"), "Value" = c(5,NA,6,NA,16,12,4,5,6,10,12,17)))
> list.tib <- split(tib, tib$Group)
> list.tib
$`A`
# A tibble: 6 x 3
Group Color Value
<fct> <fct> <dbl>
1 A Red 5
2 A Red NA
3 A Red 6
4 A Blue NA
5 A Blue 16
6 A Blue 12
$B
# A tibble: 2 x 3
Group Color Value
<fct> <fct> <dbl>
1 B Red 4
2 B Blue 17
我想使用 lapply 将 [["A"]] 中的 NA 替换为另一个值。
如果我尝试使用“
> lapply(list.tib, function(x) filter(x, is.na(Value))$Value <- 50)
Error in filter(x, is.na(Value))$Value <- 50 :
could not find function "filter<-"
我尝试了另一种方法,使用不同的格式来指定我想要的值,但最终出现了不同类型的错误。
> lapply(list.tib, function(x) x[which(is.na(x$Value)),]$Value <- 50)
Error in `$<-.data.frame`(`*tmp*`, "Value", value = 50) :
replacement has 1 row, data has 0
我认为这会引发错误,因为 [["B"]] 没有任何 NA,我正在尝试将 numeric(0) 设置为 50。
我想要一个可以提供以下输出的函数:
> list.tib
$`A`
# A tibble: 6 x 3
Group Color Value
<fct> <fct> <dbl>
1 A Red 5
2 A Red 50
3 A Red 6
4 A Blue 50
5 A Blue 16
6 A Blue 12
$B
# A tibble: 2 x 3
Group Color Value
<fct> <fct> <dbl>
1 B Red 4
2 B Blue 17
如果我执行以下操作,我就能得到这个期望的结果:
list.tib$A[which(is.na(list.tib$A$Value)),]$Value <- 50
但这不是一概而论的。我认为 lapply() 是对这项工作的要求,但我无法让它为观察的特定变量赋值。
感谢您的帮助!
【问题讨论】:
标签: r dataframe dplyr tidyverse