简体   繁体   English

如何重塑长格式数据并计算值

[英]How to reshape long format data and count the values

I think this is a basic question, but it seems to be frustrating me...我认为这是一个基本问题,但它似乎让我感到沮丧......

I am using R and have data in long format;我正在使用 R 并且有长格式的数据; a data.frame with each value a string.一个 data.frame,每个值都是一个字符串。 I want to produce a summary table of the counts of each value.我想生成每个值计数的汇总表。 So for the data:所以对于数据:

Location地点 Colour颜色
North red红色的
North blue蓝色的
North red红色的
South red红色的
South red红色的
North red红色的
South blue蓝色的
North blue蓝色的
South red红色的
South red红色的

I would like to produce the summary table:我想制作汇总表:

Location地点 red红色的 blue蓝色的
North 3 3个 2 2个
South 4 4个 1 1个

I've tried numerous attempts of reshape and cast.我尝试过无数次重塑和铸造的尝试。 I'm drawing a blank as there are no numeric 'values' in the table.我正在画一个空白,因为表格中没有数字“值”。

Using tabyl from janitor使用janitortabyl

library(janitor)
tabyl(df1, Location, Colour)
 Location blue red
    North    2   3
    South    1   4

With tidyverse, dplyr::count() first, then pivot:使用 tidyverse,首先是dplyr::count() ,然后是 pivot:

library(dplyr)
library(tidyr)

dat %>% 
  count(Location, Colour) %>% 
  pivot_wider(names_from = Colour, values_from = n)
# # A tibble: 2 × 3
#   Location  blue   red
#   <chr>    <int> <int>
# 1 North        2     3
# 2 South        1     4

In base R, you can use table() :在 base R 中,您可以使用table()

table(Location = dat$Location, dat$Colour)
# Location blue red
#    North    2   3
#    South    1   4

Note, however, that the output of table() isn't a data.frame, so may not work for you depending on what your next step is.但是请注意, table()的 output 不是 data.frame,因此可能对您不起作用,具体取决于您的下一步是什么。

Also using table() :还使用table()

df |>
  with(table(Location, Colour)) |>
  rbind() |>
  as_tibble(rownames = "Location")

  Location  blue   red
  <chr>    <int> <int>
1 North        2     3
2 South        1     4

Reproducible data可重现的数据

df = data.frame(
  Location = c("North", "North", "North", "South", "South", "North", "South", "North", "South", "South"), 
  Colour = c("red", "blue", "red", "red", "red", "red", "blue", "blue", "red", "red" )
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM