简体   繁体   中英

Replace ddply function in R

Is there a way to replicate the function of ddply? I would like to obtain correlation by groups and have as an output a dataframe with the results without having to load tha package plyr.

For example I have the dataframe (df):

Obs  Group  Val1 Val2
Obs1 Group1  1    2
Obs2 Group1  2    1
Obs3 Group2  5    6
Obs4 Group2  6    5

And I would like the output as a dataframe (Corr)

Group  Correlation
Group1 -1
Group2 -1

I currently use this function:

func <- function(df)
    {
  return(data.frame(Correlation = cor(df$Val1, df$Val2, method = "pearson")))
    }

    Corr <- ddply(df, .(Group), func)

I tried replacing ddply with:

Corr <- data.frame(sapply(split(df, df$Group),func))

But did not work.

Any ideas?

Thanks for your support.

This method just uses the base package, perhaps something like this would work?

result <- by(df, df$Group, function(x) {cor(df$Val1, df$Val2, method = "pearson")})
result.dataframe <- as.data.frame(as.matrix(result))
result.dataframe$Correlation <- rownames(result)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM