我想在带有前面值的向量中填入缺失值(不是NA
,只是''
!)。例如,如果我有一个定义为
vec <- c('Titanic', '', '', '', 'Donnie Darko', '', '', 'Twin Peaks',
'American Hustle', '')
我的输出向量是
'Titanic', 'Titanic', 'Titanic', 'Titanic', 'Donnie Darko', 'Donnie Darko',
'Donnie Darko', 'Twin Peaks', 'American Hustle', 'American Hustle'
我怎样才能做到这一点?
答案 0 :(得分:2)
在基地R中使用Reduce
,其中vec
是您的向量:
Reduce(function(x,y) ifelse(y=="", x, y), vec, accumulate=TRUE)
#[1] "Titanic" "Titanic" "Titanic" "Titanic" #"Donnie Darko"
#[6] "Donnie Darko" "Donnie Darko" "Twin Peaks" "American Hustle" #"American Hustle"
答案 1 :(得分:1)
我们也可以使用
unlist(tapply(movies, cumsum(movies !=""), FUN =
function(x) rep(x[1], length(x))), use.names = FALSE)
#[1] "Titanic" "Titanic" "Titanic" "Titanic" "Donnie Darko" "Donnie Darko" "Donnie Darko" "Twin Peaks"
#[9] "American Hustle" "American Hustle"
movies <- c('Titanic', '', '', '', 'Donnie Darko', '', '', 'Twin Peaks',
'American Hustle', '')