how to use dcast on a dataframe that has only 1 row in R

时间:2016-02-03 02:42:18

标签: r dataframe dplyr reshape2

Hi I have a dataframe like this

Start <- c("A")
End <- c("C")
Days <- c("Day1")

df2 <- data.frame(Start,End,Days)

I am trying to use dcast

df2 <- dcast(df2,Days ~ End,value.var="Days")

but it returns is

  Days    C
1 Day1 Day1

My desired output is the count

  Days    C
1 Day1    1

What am I missing here? Kindly provide some inputs on this. Is there a better way to do this using dplyr?

2 个答案:

答案 0 :(得分:1)

We can create a sequence column of 1 and then use dcast

 dcast(transform(df2, i1=1), Days~End, value.var='i1')
#  Days C
#1 Day1 1

Or another option is using the fun.aggregate

dcast(df2, Days~End, length)
#  Days C
#1 Day1 1

As the OP mentioned about dplyr, it involves using the first method as it doesn't have the fun.aggregate

 library(dplyr)
 df2 %>%
    mutate(C=1) %>%
    select(Days:C)

答案 1 :(得分:1)

Hi you are on the right track. What you need when you cast your data frame is to have a function that is applied to the aggregation during the casting.

In this case , you want something that counts the occurence of each group to do so you use the function length

dcast(df2,Days ~ End, length ) # or dcast(df, Days ~ End, table)