سؤال

In R 2.14.2 I have a matrix:

mat1=matrix(c('A','','','B'))

and I want to fill in the empty values so it becomes like this:

mat2=matrix(c('A','','','B','A','A','A','B'),2,4,byrow=T)

In other words, how do I pad the empty values?

[In Excel I would use this formula in column B: B2=if(isblank(A2),B1,A2), and copy it down].

How can I do this in R?

Henk

هل كانت مفيدة؟

المحلول

Use na.locf in package zoo. The locf means last observation carried forward, which is exactly what you are doing:

library(zoo)

x <- c('A',NA,NA,'B')
na.locf(x)

[1] "A" "A" "A" "B"

But make sure you understand the difference between NA and "" (an empty string). In Excel it may be useful to use empty strings to prevent display of formulae, but in R it's much better to use NA to indicate missing values.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top