Welcome to OGeek Q&A 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...