用列表中的字符填充NA

时间:2017-09-14 15:44:16

标签: r lapply tidyr

我有一些数据如下:

library(tidyr)
library(data.table)
thisdata <-  data.frame(numbers = c(1,3,4,5,6,1,2,4,5,6)
                     ,letters = c('A','A','A','A','A','B','B','B','B','B'))

otherdata <-  data.frame(numbers = c(1,2,3,4,5,6))

我希望将这个数据拆分为&#39;通过字母列,将两个列表合并到&#39; otherdata&#39;通过数字列,然后用该列表中的相应字母填写字母NA。所以:

out <- split(thisdata , f = thisdata$letters )
out2 <- lapply(out, function(x) merge(x,otherdata,by="numbers",all = TRUE))

然而,我无法获得“填充”。在tidyr中运作以在lapply中工作

out3 <- lapply(out2,function(x) fill(x$channel))

 Error in UseMethod("fill_") : 
  no applicable method for 'fill_' applied to an object of class "NULL" 

这是我之后的输出,但宁愿在列表格式中执行计算:

out4 <- rbindlist(out2)

out5 <- out4 %>% 
  fill(letters) %>% #default direction down
  fill(letters,.direction = "up")

   numbers letters
 1:       1       A
 2:       2       A
 3:       3       A
 4:       4       A
 5:       5       A
 6:       6       A
 7:       1       B
 8:       2       B
 9:       3       B
10:       4       B
11:       5       B
12:       6       B

1 个答案:

答案 0 :(得分:3)

fill期望数据框作为第一个参数,尝试使用fill(x, letters)管道x %>% fill(letters)magrittr

out3 <- lapply(out2,function(x) fill(x, letters))

out3
#$A
#  numbers letters
#1       1       A
#2       2       A
#3       3       A
#4       4       A
#5       5       A
#6       6       A

#$B
#  numbers letters
#1       1       B
#2       2       B
#3       3       B
#4       4       B
#5       5       B
#6       6       B

更简单的方法是使用tidyr::complete

thisdata %>% 
    complete(numbers = otherdata$numbers, letters) %>% 
    arrange(letters)

# A tibble: 12 x 2
#   numbers letters
#     <dbl>  <fctr>
# 1       1       A
# 2       2       A
# 3       3       A
# 4       4       A
# 5       5       A
# 6       6       A
# 7       1       B
# 8       2       B
# 9       3       B
#10       4       B
#11       5       B
#12       6       B