1

I was wondering if there was a way to take a "cross-product" of data frames with non-numeric entries. I have a single-column data frame df.RICS with strings as entries (length 235), and another df.dates with dates as entries (length 3004). I want a data frame with each date matched up to each string in df.RICS:

    dates
1   2004-04-23
2   2004-04-24
3   2004-04-25
4   2004-04-26
5   2004-04-27
6   2004-04-28
7   2004-04-29
8   2004-04-30
9   2004-05-01
10  2004-05-02

    RICS
1   AA.N
2   AAP
3   AAP.N
4   AAPL.O
5   ABGL.L

Can I use expand.grid(df.RICS, df.dates) without converting to numeric values?

Right now all I have is:

> expand.grid(datesAsVec, RICSAsVec, stringsAsFactors = TRUE)
        Var1 Var2
1 2004-04-23 AA.N
Warning message:
In format.data.frame(x, digits = digits, na.encode = FALSE) :
  corrupt data frame: columns will be truncated or padded with NAs
4

2 回答 2

2

you're looking for expand.grid

于 2012-06-01T15:17:19.480 回答
1
  1. If your operation works with character data, you could convert the data.frames to character matrices, outer works on these.

    > df <- data.frame (a = LETTERS [1:3], b = 4:6, c = Sys.Date ())
    > df
      a b          c
    1 A 4 2012-06-01
    2 B 5 2012-06-01
    3 C 6 2012-06-01
    > sapply (df, as.character)
         a   b   c           
    [1,] "A" "4" "2012-06-01"
    [2,] "B" "5" "2012-06-01"
    [3,] "C" "6" "2012-06-01"
    > class (sapply (df, as.character))
    [1] "matrix"
    
  2. If the function is vectorized, nstead of using outer you could also repeat the two matices appropriately and directly use the function.

  3. If the function doesn't work on character, it's going to be more complicated... But you could have a look at POSIXct.

于 2012-06-01T15:52:47.137 回答