包含两个键列的gather()

包含两个键列的gather(),r,tidyr,R,Tidyr,我有一个数据集,它有两行数据,并希望使用类似于gather()的方法对它们进行整理,但不知道如何将这两行都标记为键列 数据如下所示: Country US Canada US org_id 332 778 920 02-15-20 25 35 54 03-15-20 30 10 60 我希望它看起来像 country org_id date purchase_price US 332 02-15-20 2

我有一个数据集,它有两行数据,并希望使用类似于gather()的方法对它们进行整理,但不知道如何将这两行都标记为键列

数据如下所示:

Country  US   Canada  US 
org_id   332  778     920
02-15-20 25   35      54
03-15-20 30   10      60
我希望它看起来像

country  org_id  date      purchase_price 
US       332      02-15-20 25
Canada   778      02-15-20 35
US       920      02-15-20 54
US       332      03-15-20 30
Canada   778      03-15-20 10
US       920      03-15-20 60

例如,我知道gather()可以将国家行移动到列中,但是有没有办法将国家和组织id行都移动到列中?

在数据中使用重复的列名不是一个好主意,因此我将重命名其中一个列名

names(df)[4] <- 'US_1'
数据

df <- structure(list(Country = c("org_id", "02-15-20", "03-15-20"), 
    US = c(332L, 25L, 30L), Canada = c(778L, 35L, 10L), US = c(920L, 
    54L, 60L)), class = "data.frame", row.names = c(NA, -3L))

df在数据中使用重复的列名不是一个好主意,因此我将重命名其中一个列名

names(df)[4] <- 'US_1'
数据

df <- structure(list(Country = c("org_id", "02-15-20", "03-15-20"), 
    US = c(332L, 25L, 30L), Canada = c(778L, 35L, 10L), US = c(920L, 
    54L, 60L)), class = "data.frame", row.names = c(NA, -3L))

df首先,我们将
Country
org\u id

library(tidyverse)

data <- set_names(data, paste(names(data), data[1,], sep = "-")) 
data
  Country-org_id US-332 Canada-778 US-920
1         org_id    332        778    920
2       02-15-20     25         35     54
3       03-15-20     30         10     60
库(tidyverse)
数据%
重命名(日期=`Country-org\u id`)%>%
pivot_更长(cols=-date,value_to=“price”)%>%
分开(col=name,into=c(“国家”,“组织id”),sep=“-”)
df
#一个tibble:6x4
日期国家组织标识价格
102-15-20美国332 25
2 02-15-20加拿大778 35
302-15-20美国920 54
4 03-15-20美国332 30
5 03-15-20加拿大778 10
6 03-15-20美国920 60

首先,我们将
国家
组织id

library(tidyverse)

data <- set_names(data, paste(names(data), data[1,], sep = "-")) 
data
  Country-org_id US-332 Canada-778 US-920
1         org_id    332        778    920
2       02-15-20     25         35     54
3       03-15-20     30         10     60
库(tidyverse)
数据%
重命名(日期=`Country-org\u id`)%>%
pivot_更长(cols=-date,value_to=“price”)%>%
分开(col=name,into=c(“国家”,“组织id”),sep=“-”)
df
#一个tibble:6x4
日期国家组织标识价格
102-15-20美国332 25
2 02-15-20加拿大778 35
302-15-20美国920 54
4 03-15-20美国332 30
5 03-15-20加拿大778 10
6 03-15-20美国920 60