填写R中数据框中的值?

时间:2016-05-11 16:57:02

标签: r dataframe dplyr

假设我有这个数据框:

  times vals
1     1    2
2     3    4
3     7    6

设置

foo <- data.frame(times=c(1,3,7), vals=c(2,4,6))

我想要这个:

  times vals
1     1    2
2     2    2
3     3    4
4     4    4
5     5    4
6     6    4
7     7    6

也就是说,我想从1到7填写所有时间,并从不超过给定时间的最新时间填写val。

我有一些代码可以使用dplyr来完成它,但它很难看。建议更好?

library(dplyr)

foo <- merge(foo, data.frame(times=1:max(foo$times)), all.y=TRUE)
foo2 <- merge(foo, foo, by=c(), suffixes=c('', '.1'))

foo2 <- foo2 %>% filter(is.na(vals) & !is.na(vals.1) & times.1 <= times) %>%
  group_by(times) %>% arrange(-times.1) %>% mutate(rn = row_number()) %>%
  filter(rn == 1) %>%
  mutate(vals = vals.1,
         rn = NULL,
         vals.1 = NULL,
         times.1 = NULL)

foo <- merge(foo, foo2, by=c('times'), all.x=TRUE, suffixes=c('', '.2'))
foo <- mutate(foo,
              vals = ifelse(is.na(vals), vals.2, vals),
              vals.2 = NULL)

4 个答案:

答案 0 :(得分:10)

这是一个标准的滚动连接问题:

library(data.table)

setDT(foo)[.(1:7), on = 'times', roll = T]
#   times vals
#1:     1    2
#2:     2    2
#3:     3    4
#4:     4    4
#5:     5    4
#6:     6    4
#7:     7    6

以上是devel版本(1.9.7+),它更适合连接期间的列匹配。对于1.9.6,您仍需要为内部表指定列名:

setDT(foo)[.(times = 1:7), on = 'times', roll = T]

答案 1 :(得分:6)

使用approx

data.frame(times = 1:7, 
           vals = unlist(approx(foo, xout = 1:7, method = "constant", f = 0)[2], use.names = F))

  times vals
1     1    2
2     2    2
3     3    4
4     4    4
5     5    4
6     6    4
7     7    6

答案 2 :(得分:5)

dplyrtidyr选项:

library(dplyr)
library(tidyr)

foo %>%
 right_join(data_frame(times = min(foo$times):max(foo$times))) %>%
 fill(vals)
# Joining by: "times"
#   times vals
# 1     1    2
# 2     2    2
# 3     3    4
# 4     4    4
# 5     5    4
# 6     6    4
# 7     7    6

答案 3 :(得分:4)

这是一个更长,更冗长的基础R解决方案:

# calculate the number of repetitions needed for vals variable
reps <- c(with(foo, times[2:length(times)]-times[1:length(times)-1]), 1)

# get result
fooDoneIt <- data.frame(times = min(foo$times):max(foo$times),
              vals = rep(foo$vals, reps))