Roy1245
Roy1245

Reputation: 507

converting row heading to column and count the value

I have a dataframe which looks like:

ID     Fig1  Fig2   TER1   TER2    TER3
ERT-1  50     25    A      A       C
ERT-2  80     35    B      C       B
ERT-5  10     75    C      C       A

There are only three distinct values in column TER1, TER2 and TER3, want to know the count of each value with corresponding to the ID.

I have tried dcast but it couldn't work.

Required Dataframe:

XYZ    A    B    C
TER1   1    1    1
TER2   1    0    2
TER3   1    1    1

Upvotes: 0

Views: 38

Answers (1)

Sotos
Sotos

Reputation: 51592

Here is an idea via dplyr. You need to gather your columns of interest first, and then count, i.e.

library(dplyr)

df %>%
  gather(var, val, -c(1:3)) %>%
  select(var, val) %>%
  table() %>%
  as.data.frame.matrix() %>%
  rownames_to_column('XYZ')

which gives,

   XYZ A B C
1 TER1 1 1 1
2 TER2 1 0 2
3 TER3 1 1 1

Upvotes: 1

Related Questions