[英]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 ![]() |
2 ![]() |
South![]() |
4 ![]() |
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
使用
janitor
的tabyl
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.