Using approx function on grouped data in R

谁说胖子不能爱 提交于 2020-01-07 06:56:10

问题


I have a big data set with columns Id, Vg, Device, Die, W ,L and others (not relevant to this question). I want to interpolate Vg at a given value of Id but this operation has to be performed on data grouped by column Device and Die.

My sample data looks like

Die     Device      Id      Vg     W   L 
  1    Device1       1       0    10   1  
  1    Device1     1.2     0.1    10   1  
  1    Device1     1.3     0.2    10   1
  1    Device2       1       0    10   2
  1    Device2     1.2     0.1    10   2  
  1    Device2     1.3     0.2    10   2
  1    Device3       1       0    10   3
  1    Device3     1.2     0.1    10   3  
  1    Device3     1.3     0.2    10   3

Each die has 22 unique devices. There are 67 dies and 22 Device names on each die are the same. Therefore if I interpolate Vg for Id=1.25, I expect to get 22*67 values of Vg for Id=1.25.

Here is the code I am trying

data_tidy%>%
  group_by(Die,Device)%>% #Die is numeric, Device is factor
  mutate(Vt=approx(x=log10(Id),y=Vg,xout=log10(3e-8*W/L))$y)

This is similar to what is suggested here and I am copying the suggested code from the link below

df %>%
  group_by(variable) %>%
  arrange(variable, event.date) %>%
  mutate(time=seq(1,n())) %>%
  mutate(ip.value=approx(time,value,time)$y) %>%
  select(-time)

However, when I execute my code above I get an error message saying

Error: impossible to replicate vector of size 18


回答1:


Here's a data.table solution:

library(data.table)
f <- function(x) setDT(df)[,approx(Id,Vg,x), by=list(Device,Die)]
f(1.25)
#     Device Die    x    y
# 1: Device1   1 1.25 0.15
# 2: Device2   1 1.25 0.15
# 3: Device3   1 1.25 0.15

Here the column y is the interpolated value.



来源:https://stackoverflow.com/questions/32513965/using-approx-function-on-grouped-data-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!