Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

r - Using approx() with groups in dplyr

I am trying to use approx() and dplyr to interpolate values in an existing array. My initial code looks like this ...

p = c(1,1,1,2,2,2)
q = c(1,2,3,1,2,3)
r = c(1,2,3,4,5,6)

Inputs<- data.frame(p,q,r)

new.inputs= as.numeric(c(1.5,2.5))

library(dplyr)

Interpolated <- Inputs %>%
        group_by(p) %>%
        arrange(p, q) %>%
        mutate(new.output=approx(x=q, y=r, xout=new.inputs)$y)

I expect to see 1.5, 2.5, 4.5, 5.5 but instead I get

Error: incompatible size (2), expecting 3 (the group size) or 1

Can anyone tell me where I am going wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can get the values you expect using dplyr.

library(dplyr)
Inputs %>%
  group_by(p) %>%
  arrange(p, q, .by_group = TRUE) %>%
  summarise(new.outputs = approx(x = q, y = r, xout = new.inputs)$y)

#     p  new.outputs
#  <dbl>       <dbl>
#     1         1.5
#     1         2.5
#     2         4.5
#     2         5.5

You can also get the values you expect using the ddply function from plyr.

library(plyr)

# Output as coordinates
ddply(Inputs, .(p), summarise, new.output = paste(approx(
  x = q, y = r, xout = new.inputs
)$y, collapse = ","))

# p new.output
# 1    1.5,2.5
# 2    4.5,5.5

#######################################

# Output as flattened per group p
ddply(Inputs,
      .(p),
      summarise,
      new.output = approx(x = q, y = r, xout = new.inputs)$y)

# p new.output
# 1        1.5
# 1        2.5
# 2        4.5
# 2        5.5


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...