如何为 R 中另一列的每个级别创建一个列?
How to create a column for each level of another column in R?
我要实现的目标是扩展数据框,我将在其中为 R 中特定列的每个级别创建一个新列。这是初始数据框和数据框 I 的示例我正在努力实现:
原始数据框:
record crop_land fishing_ground
BiocapPerCap 1.5 3.4
Consumption 2.3 0.5
目标数据框:
crop_land.BiocapPerCap crop_land.Consumption fishing_ground.BiocapPerCap fishing_ground.Consumption
1.5 2.3 3.4 0.5
使用 tidyr 是一种选择。
tidyr::pivot_longer()
将 crop_land
和 fishing_ground
转换为变量值对。 tidyr::unite()
将记录和变量合并为新名称。
tidyr::pivot_wider()
创建您想要的宽数据框。
library(tidyr)
library(magrittr) # for %>%
tst <- data.frame(
record = c("BiocapPerCap", "Consumption"),
crop_land = c(1.5, 2.3),
fishing_ground = c(3.4, 0.5)
)
pivot_longer(tst, -record) %>%
unite(new_name, record, name, sep = '.') %>%
pivot_wider(names_from = new_name, values_from = value)
我们可以使用 tidyr
包中的 pivot_wider
,如下所示。
library(tidyr)
library(magrittr)
dat2 <- dat %>%
pivot_wider(names_from = "record", values_from = c("crop_land", "fishing_ground"),
names_sep = ".")
dat2
# # A tibble: 1 x 4
# crop_land.BiocapPerCap crop_land.Consumption fishing_ground.BiocapPer~ fishing_ground.Consumpti~
# <dbl> <dbl> <dbl> <dbl>
# 1 1.5 2.3 3.4 0.5
数据
dat <- read.table(text = "record crop_land fishing_ground
BiocapPerCap 1.5 3.4
Consumption 2.3 0.5",
header = TRUE, stringsAsFactors = FALSE)
我要实现的目标是扩展数据框,我将在其中为 R 中特定列的每个级别创建一个新列。这是初始数据框和数据框 I 的示例我正在努力实现:
原始数据框:
record crop_land fishing_ground
BiocapPerCap 1.5 3.4
Consumption 2.3 0.5
目标数据框:
crop_land.BiocapPerCap crop_land.Consumption fishing_ground.BiocapPerCap fishing_ground.Consumption
1.5 2.3 3.4 0.5
使用 tidyr 是一种选择。
tidyr::pivot_longer()
将 crop_land
和 fishing_ground
转换为变量值对。 tidyr::unite()
将记录和变量合并为新名称。
tidyr::pivot_wider()
创建您想要的宽数据框。
library(tidyr)
library(magrittr) # for %>%
tst <- data.frame(
record = c("BiocapPerCap", "Consumption"),
crop_land = c(1.5, 2.3),
fishing_ground = c(3.4, 0.5)
)
pivot_longer(tst, -record) %>%
unite(new_name, record, name, sep = '.') %>%
pivot_wider(names_from = new_name, values_from = value)
我们可以使用 tidyr
包中的 pivot_wider
,如下所示。
library(tidyr)
library(magrittr)
dat2 <- dat %>%
pivot_wider(names_from = "record", values_from = c("crop_land", "fishing_ground"),
names_sep = ".")
dat2
# # A tibble: 1 x 4
# crop_land.BiocapPerCap crop_land.Consumption fishing_ground.BiocapPer~ fishing_ground.Consumpti~
# <dbl> <dbl> <dbl> <dbl>
# 1 1.5 2.3 3.4 0.5
数据
dat <- read.table(text = "record crop_land fishing_ground
BiocapPerCap 1.5 3.4
Consumption 2.3 0.5",
header = TRUE, stringsAsFactors = FALSE)