如何为R中另一个列的每个级别创建列?

问题描述 投票:1回答:2

我要实现的目标是扩展数据框,在其中我将为R中特定列的每个级别创建一个新列。这是初始数据框和我要尝试的数据框的示例实现:

原始数据框:

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
r dataframe calculated-columns
2个回答
0
投票

使用提迪尔是一种选择。

tidyr::pivot_longer()crop_landfishing_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)


0
投票

我们可以如下使用pivot_wider包中的tidyr

library(tidyr)

dat2 <- dat %>%
  pivot_wider(names_from = "record", values_from = c("crop_land", "fishing_ground"))
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

DATA

dat <- read.table(text = "record           crop_land     fishing_ground
BiocapPerCap     1.5           3.4
Consumption      2.3           0.5",
                  header = TRUE, stringsAsFactors = FALSE)
© www.soinside.com 2019 - 2024. All rights reserved.