cdeterman
cdeterman

Reputation: 19970

R: expand data.frame values

I have a data.frame like so:

df <- data.frame(x = c(998,994,992,990,989,988), y = seq(0.5, 3, by = 0.5))
df

    x   y
1 998 0.5
2 994 1.0
3 992 1.5
4 990 2.0
5 989 2.5
6 988 3.0

I would like to expand it so the values in x are exactly 1 apart so the final data.frame looks like this:

    x   y
1  998 0.5
2  997 0.5
3  996 0.5
5  995 0.5
6  994 1.0
7  993 1.0
8  992 1.5
9  991 1.5
10 990 2.0
11 989 2.5
12 988 3.0

Upvotes: 3

Views: 114

Answers (2)

erc
erc

Reputation: 10131

You can also use approx:

data.frame(approx(df, xout=max(df$x):min(df$x), method="constant", f=1))

     x   y
1  998 0.5
2  997 0.5
3  996 0.5
4  995 0.5
5  994 1.0
6  993 1.0
7  992 1.5
8  991 1.5
9  990 2.0
10 989 2.5
11 988 3.0

Upvotes: 11

Cath
Cath

Reputation: 24074

you can try with function na.locf from package zoo:

all_values <- max(df$x):min(df$x)
na.locf(merge(df, x=all_values, all=TRUE)[rev(seq(all_values)),])
#      x   y
# 11 998 0.5
# 10 997 0.5
# 9  996 0.5
# 8  995 0.5
# 7  994 1.0
# 6  993 1.0
# 5  992 1.5
# 4  991 1.5
# 3  990 2.0
# 2  989 2.5
# 1  988 3.0

NB

As suggested by @Ananta and @ProcrastinatusMaximus, another option is to set fromLast=TRUE in the na.locf call (if you need to have x in descending order, you'll need to sort the data.frame afterwards):

na.locf(merge(df, x=all_values, all=TRUE), fromLast=TRUE)

Upvotes: 7

Related Questions