-1

R新手(ish)。我已经编写了一些在 R 中使用for()循环的代码。我想以矢量化形式重写它,但它不起作用。

用于说明的简化示例:

library(dplyr)

x <- data.frame(name = c("John", "John", "John", "John", "John", "John", "John", "John", "Fred", "Fred"),
                year = c(1, NA, 2, 3, NA, NA, 4, NA, 1, NA))

## if year is blank and name is same as name from previous row
##    take year from previous row
## else
##    stick with the year you already have

# 1. Run as a loop

x$year_2 <- NA
x$year_2[1] <- x$year[1]                

for(row_idx in 2:10)
{
  if(is.na(x$year[row_idx]) & (x$name[row_idx] == x$name[row_idx - 1]))
  {
    x$year_2[row_idx] = x$year_2[row_idx - 1]
  }
  else
  {
    x$year_2[row_idx] = x$year[row_idx]
  }
}  

# 2. Attempt to vectorise

x <- data.frame(name = c("John", "John", "John", "John", "John", "John", "John", "John", "Fred", "Fred"),
                year = c(1, NA, 2, 3, NA, NA, 4, NA, 1, NA))

x$year_2 <- ifelse(is.na(x$year) & x$name == lead(x$name),
                   lead(x$year_2),
                   x$year)

我认为矢量化版本被搞砸了,因为它有一个循环性(即x$year_2出现在 的两侧<-)。有没有办法解决这个问题?

谢谢你。

4

4 回答 4

4

我建议你使用已经建立的功能,R一开始感觉很难,因为我们被训练去重新发明轮子,不要这样做。

library(tidyverse)

x <- data.frame(name = c("John", "John", "John", "John", "John", "John", "John", "John", "Fred", "Fred"),
                year = c(1, NA, 2, 3, NA, NA, 4, NA, 1, NA))


x %>% 
  group_by(name) %>% 
  tidyr::fill(year)
于 2019-12-20T14:12:06.483 回答
1

如果您使用dplyr/ tidyverse

library(dplyr)
library(tidyr)
x %>% 
  group_by(name) %>% 
  fill("year")

   name   year
   <fct> <dbl>
 1 John      1
 2 John      1
 3 John      2
 4 John      3
 5 John      3
 6 John      3
 7 John      4
 8 John      4
 9 Fred      1
10 Fred      1
于 2019-12-20T14:11:56.163 回答
0

如果您知道数据框始终处于这种排序中,那么通过NAs使用最新的非缺失值填充以下内容应该对您有用。

library(zoo)
x <- data.frame(name = c("John", "John", "John", "John", "John", "John", "John", "John", "Fred", "Fred"),
                year = c(1, NA, 2, 3, NA, NA, 4, NA, 1, NA))
x$year_2 <- na.locf(x$year)
x

如果您不想加载zoo包,这也可以:

repeat_last = function(x, forward = TRUE, maxgap = Inf, na.rm = FALSE) {
  if (!forward) x = rev(x)           # reverse x twice if carrying backward
  ind = which(!is.na(x))             # get positions of nonmissing values
  if (is.na(x[1]) && !na.rm)         # if it begins with NA
    ind = c(1,ind)                 # add first pos
  rep_times = diff(                  # diffing the indices + length yields how often
    c(ind, length(x) + 1) )          # they need to be repeated
  if (maxgap < Inf) {
    exceed = rep_times - 1 > maxgap  # exceeding maxgap
    if (any(exceed)) {               # any exceed?
      ind = sort(c(ind[exceed] + 1, ind))      # add NA in gaps
      rep_times = diff(c(ind, length(x) + 1) ) # diff again
    }
  }
  x = rep(x[ind], times = rep_times) # repeat the values at these indices
  if (!forward) x = rev(x)           # second reversion
  x
}

x$year_3 <- repeat_last(x$year)
x
于 2019-12-20T14:13:35.487 回答
0

可以通过下面的代码实现 base R 中的一种简单方法

x <- within(x, year <- subset(year,!is.na(year))[cumsum(!is.na(year))])

或者

x$year <- with(x, subset(year,!is.na(year))[cumsum(!is.na(year))])

这样

> x
   name year
1  John    1
2  John    1
3  John    2
4  John    3
5  John    3
6  John    3
7  John    4
8  John    4
9  Fred    1
10 Fred    1
于 2019-12-20T14:24:27.573 回答