You asked for base R but also said or using other methods. So for
completeness here is a solution using Tidyverse
library(tidyverse)
data_original <- data.frame(
year = c('1990', '1999', '1990', '1989'),
size = c('s', 'l', 'xl', 'xs'), n = c(99, 33, 3, 4) )
data_original |>
pivot_wider(
Well, if you know the column subscripts you need, just forget about the names!
I would just write a (one-liner) function to do it for any data frame:
myfun <- function(dat)tapply(dat[,3], dat[,1:2], sum)
## dat[,1:2] is a list because it's a data frame and all data frames are lists
myfun(data_or
Bert,
Thanks! I'm pretty sure what you provided gets me to what I was
looking for, and is much simpler. I really appreciate your help.
A follow-up question:
I adjusted the code to not use "hard-coded" column names.
mat2 <- with(data_original, tapply( get(names(data_original)[3]),
list( get(names(
"As my end result, I want a matrix or data frame, with one row for each
year, and one column for each category."
If I understand you correctly, no reshaping gymnastics are needed --
just use ?tapply:
set.seed(1)
do <- data.frame(year = rep(1990:1999, length = 50),
category = sample(1:5, size = 5
As my end result, I want a matrix or data frame, with one row for each
year, and one column for each category.
On Fri, Oct 21, 2022 at 6:23 PM Kelly Thompson wrote:
>
> # I think this might be a better example.
>
> # I have data presented in a "vertical" dataframe as shown below in
> data_origina
# I think this might be a better example.
# I have data presented in a "vertical" dataframe as shown below in
data_original.
# I want this data in a matrix or "grid", as shown below.
# What I show below seems like one way this can be done.
# My question: Are there easier or better ways to do this
This operation goes by a variety of names... reshape (stats), cast (reshape2),
spread (tidyr), and pivot_wider (tidyr).
The stats package reshape function is built-in, but uses terminology that can
be confusing, and may not come out sorted the way you want so pre-converting to
factor or post-so
###
#I have data presented in a "vertical" data frame as shown below in
data_original.
#I want this data in a matrix or "grid", as shown below.
#What I show below seems like one way this can be done.
#My question: Are there easier or better ways to do this, especially
in Base R, and also in R pack
8 matches
Mail list logo