Great work as usual, cpad. Enjoy your weekend.
• 0 views
•
link
Dear all,
i have this table. does someone know how to de-aggregate it ?
plant tissue count
tomato leaf 1
tomato root 4
tomato shoot 5
solanus leaf 3
solanus root 2
solanus shoot 4
what i want is a dataframe like that:
leaf root shoot
tomato 1 4 5
solanus 3 2 4
thanks in advance for you tips
Buenas tardes amiga/o,
You can use dcast():
df
plant tissue count
1 tomato leaf 1
2 tomato root 4
3 tomato shoot 5
4 solanus leaf 3
5 solanus root 2
6 solanus shoot 4
require(data.table)
dcast(data = df, formula = plant ~ tissue, value.var = 'count')
plant leaf root shoot
1 solanus 3 2 4
2 tomato 1 4 5
Kevin
Base R:
> xtabs(count ~ ., data = test)
tissue
plant leaf root shoot
solanus 3 2 4
tomato 1 4 5
> test
plant tissue count
1 tomato leaf 1
2 tomato root 4
3 tomato shoot 5
4 solanus leaf 3
5 solanus root 2
6 solanus shoot 4
out of R, with datamash:
$ datamash -sH crosstab 1,2 unique 3 <test.txt
GroupBy(plant) GroupBy(tissue) unique(count)
leaf root shoot
solanus 3 2 4
tomato 1 4 5
Great work as usual, cpad. Enjoy your weekend.
Thanks Kevin Blighe and enjoy your weekend :).
Tidy way
library(tidyverse)
data <- tibble(plant = c("tomato","tomato","tomato","solanus" ,"solanus","solanus") , tissue = c("leaf" ,"root","shoot","leaf","root","shoot") , count = c(1,4,5,3,2,4))
> data
# A tibble: 6 x 3
plant tissue count
<chr> <chr> <dbl>
1 tomato leaf 1
2 tomato root 4
3 tomato shoot 5
4 solanus leaf 3
5 solanus root 2
6 solanus shoot 4
data %>% spread(key = tissue , value = count)
# A tibble: 2 x 4
plant leaf root shoot
<chr> <dbl> <dbl> <dbl>
1 solanus 3 2 4
2 tomato 1 4 5
Log in to answer this question.
See below SO post, there are many alternatives, this is called "convert from long-to-wide format":
I add another option to solve this with tidyr:
1. reproduce the same table
2. make it wider