I have a data frame with a sequence in 'col1' and values in 'col2':
col1 col2
2 0.02
5 0.12
9 0.91
13 1.13
I want to expand the irregular sequence in 'col1' with a regular sequence from 1 to 13. For the values in 'col1' which are missing in the original data, I want 'col2' to have the value 0
in the final output:
col1 col2
1 0
2 0.02
3 0
4 0
5 0.12
6 0
7 0
8 0
9 0.91
10 0
11 0
12 0
13 1.13
How can I do this in R?
Here is a function that uses
expandRows
fromsplitstackshape
package,Another way would be:
Axeman's answer is really sweet, though.
Edit: Data used --
DISCLAIMER: This should really not be used for big datasets. I tried it with 1k rows and it was done in a heartbeat, but my second test with 100k rows is running for minutes now, which really emphasizes Axeman's concerns in his comment.
We can use
base R
withmerge
andreplace
I didn't see a simple
merge
solution, so here is one:The second line is replacing the
NA
's from themerge
(left outer join) with zeros. As @Axeman points out, this can also be accomplished by:The result is:
or
or
But this will leave
NA
s instead of zeros.There are already some interesting answers here.
Just to hop in, we can create a sequence of numbers from 1 to
max(col1)
and then get the respective value ofcol2
usingmatch
This will give
NA
s instead of 0. If we need 0's,