将我自己的函数应用于dplyr tbl_df

时间:2015-10-03 15:47:01

标签: r dplyr

以前我已经完成了这个功能:

vap.vector <- function (x, y) {
    y[is.infinite(y)] <- NA
    y[y == 0] <- NA
    logtasa <- log(y)
    datos <- data.frame(x, logtasa)
    datos <- na.omit(datos)
    lmdatos <- lm(logtasa ~ x, data = datos)
    es <- qt(0.975, lmdatos$df.residual) * summary(lmdatos)$coefficients[2, 2]
    vap <- summary(lmdatos)$coefficients[2, 1]
    vec <- c(vap = vap, es = es, lwr = vap - es, upr = vap + es)
    round((1 - exp(vec)) * -100, 2)
}

vap_ <- function (df, x, y) {
    x = lazyeval::lazy_eval(x, df)
    y = lazyeval::lazy_eval(y, df)
    vap.vector(x, y)
}

vap <- function (df, x, y) 
vap_(df, lazyeval::lazy(x), lazyeval::lazy(y))

我有这个数据集

https://drive.google.com/file/d/0Bw2XRcfksYZuX1R5bG9oZzdhZ2M/view?usp=sharing

我想做:

tbl_df %>% group_by(code, sex) %>% vap(year, values)

tbl_df %>% group_by(code, sex) %>%
           summarise(vap = vap.vector(year, values)[1],
                     lwr = vap.vector(year, values)[3],
                     upr = vap.vector(year, values)[4]
 )

结果是一个带有代码,性别和vap,lwr和upr列的data.frame。

但我不能这样做。我得到了第二个方法:

Error: 0 (non-NA) cases

有一种简单的方法可以做到这一点,或者我需要成为@hadley

我正在使用R 3.2.2和dplyr 0.4.3在Windows上工作。 提前谢谢......

1 个答案:

答案 0 :(得分:1)

您只需要使用void checkOnClick(object obj, EventArgs ea) { tcpClient = new TcpClient("127.0.0.1", 1234); ns = tcpClient.GetStream(); sr = new StreamReader(ns); sw = new StreamWriter(ns); //sending ID sw.WriteLine(newText.Text); sw.Flush(); //receiving validity of ID data = sr.ReadLine(); int validid = int.Parse(data); if (validid == 0) { newText.Text="Valid data"; check.Enabled = false; } else { newText.Text="Invalid data. Please retry"; // Now the code will exit and your user could retry } }

do

产生:

vap.vector <- function (x, y) {
    y[is.infinite(y)] <- NA
    y[y == 0] <- NA
    logtasa <- log(y)
    datos <- data.frame(x, logtasa)
    datos <- na.omit(datos)
    lmdatos <- lm(logtasa ~ x, data = datos)
    es <- qt(0.975, lmdatos$df.residual) * summary(lmdatos)$coefficients[2, 2]
    vap <- summary(lmdatos)$coefficients[2, 1]
    vec <- c(vap = vap, es = es, lwr = vap - es, upr = vap + es)
    round((1 - exp(vec)) * -100, 2)
}

Data <- read.table("dataset.csv", sep = ",", header = TRUE)

library(dplyr)
Results <- 
    Data %>% 
    group_by(code, sex) %>% 
    do(as.data.frame(t(vap.vector(.$year, .$values)[-2])))