Davy Kavanagh
Davy Kavanagh

Reputation: 4959

R: converting dataframe to table

I have a dataframe in R with three variables named for example df$V1, df$V2, df$V3. df$V1 and df$V2 are both factors, while df$V3 is numeric.

df <- data.frame(
  V1 = letters[1:4],
  V2 = rep(LETTERS[1:3], each = 4),
  V3 = 1:12
)

I am looking for a way to create a table that contains the values in df$V3, with df$V1 as the rows, and df$V2 as the columns.

I tried variations on table, but didn't get anywhere. Perhaps someone could help, Thanks in advance, Davy.

Upvotes: 8

Views: 30587

Answers (2)

Aaron - mostly inactive
Aaron - mostly inactive

Reputation: 37824

This is an alternative to table:

xtabs(V3 ~ V1 + V2, df)

Upvotes: 20

nullglob
nullglob

Reputation: 7053

As mentioned by ran2, you can use the reshape package. Here is an example:

df <- data.frame(V1 = factor(sample(letters[1:5],100,replace=TRUE)),
                 V2 = factor(toupper(sample(letters[1:5],100,replace=TRUE))),
                 V3 = runif(100))
library(reshape)
cast(df, V1 ~ V2, mean)

Upvotes: 7

Related Questions