重组 table
To reorganize the table
我有一个table如下:
LocationName
Date
Date
Booth
2020-11-06
2021-03-08
Charleswood
2020-11-17
2021-03-08
Fort Garry
2017-08-29
2018-07-20
我想要这个table:
LocationName
Date
Booth
2020-11-06
Booth
2021-03-08
Charleswood
2020-11-17
Charleswood
2021-03-08
Fort Garry
2020-11-06
Fort Garry
2021-03-08
我在 R 中做什么?
尝试data.table
选项
> setDT(df)[, .(Date = unlist(.SD)),LocationName]
LocationName Date
1: Booth 2020-11-06
2: Booth 2021-03-08
3: Charleswood 2020-11-17
4: Charleswood 2021-03-08
5: Fort Garry 2017-08-29
6: Fort Garry 2018-07-20
数据
> dput(df)
structure(list(LocationName = c("Booth", "Charleswood", "Fort Garry"
), Date = c("2020-11-06", "2020-11-17", "2017-08-29"), Date = c("2021-03-08",
"2021-03-08", "2018-07-20")), class = "data.frame", row.names = c(NA,
-3L))
您可以获取长格式的数据。
使用tidyverse
:
library(tidyverse)
df %>%
pivot_longer(cols = -LocationName, values_to = 'Date') %>%
select(-name)
# LocationName Date
# <chr> <chr>
#1 Booth 2020-11-06
#2 Booth 2021-03-08
#3 Charleswood 2020-11-17
#4 Charleswood 2021-03-08
#5 Fort Garry 2017-08-29
#6 Fort Garry 2018-07-20
使用data.table
:
library(data.table)
melt(setDT(df), id.vars = 'LocationName', value.name = "Date")[, variable := NULL][]
我有一个table如下:
LocationName | Date | Date |
---|---|---|
Booth | 2020-11-06 | 2021-03-08 |
Charleswood | 2020-11-17 | 2021-03-08 |
Fort Garry | 2017-08-29 | 2018-07-20 |
我想要这个table:
LocationName | Date |
---|---|
Booth | 2020-11-06 |
Booth | 2021-03-08 |
Charleswood | 2020-11-17 |
Charleswood | 2021-03-08 |
Fort Garry | 2020-11-06 |
Fort Garry | 2021-03-08 |
我在 R 中做什么?
尝试data.table
选项
> setDT(df)[, .(Date = unlist(.SD)),LocationName]
LocationName Date
1: Booth 2020-11-06
2: Booth 2021-03-08
3: Charleswood 2020-11-17
4: Charleswood 2021-03-08
5: Fort Garry 2017-08-29
6: Fort Garry 2018-07-20
数据
> dput(df)
structure(list(LocationName = c("Booth", "Charleswood", "Fort Garry"
), Date = c("2020-11-06", "2020-11-17", "2017-08-29"), Date = c("2021-03-08",
"2021-03-08", "2018-07-20")), class = "data.frame", row.names = c(NA,
-3L))
您可以获取长格式的数据。
使用tidyverse
:
library(tidyverse)
df %>%
pivot_longer(cols = -LocationName, values_to = 'Date') %>%
select(-name)
# LocationName Date
# <chr> <chr>
#1 Booth 2020-11-06
#2 Booth 2021-03-08
#3 Charleswood 2020-11-17
#4 Charleswood 2021-03-08
#5 Fort Garry 2017-08-29
#6 Fort Garry 2018-07-20
使用data.table
:
library(data.table)
melt(setDT(df), id.vars = 'LocationName', value.name = "Date")[, variable := NULL][]