本文介绍了对dplyr中的组使用rox()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用 approx()
和 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)
我希望看到1.5、2.5、4.5、5.5,但我得到
I expect to see 1.5, 2.5, 4.5, 5.5 but instead I get
谁能告诉我我要去哪里错了?
Can anyone tell me where I am going wrong?
推荐答案
您可以使用 dplyr
获得所需的值.
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
您还可以使用 plyr
中的 ddply
函数获得所需的值.
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
这篇关于对dplyr中的组使用rox()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!