如何从一列引用其他列的名称并创建新列

问题描述

我有一张桌子,例如

+---------+---------+--------+--------+--------+
| Product | Classif | Type 1 | Type 2 | Type 3 |
+---------+---------+--------+--------+--------+
| a       | Type 1  |      2 |      6 |      8 |
| b       | Type 2  |      3 |      9 |     11 |
| c       | Type 3  |      5 |     10 |     15 |
+---------+---------+--------+--------+--------+

哪里有我的产品列表和它们的分类。产品和分类间的匹配足以确定其价格(在第3至5列中)。 我想要一个新列,根据其类型显示每种产品的价格,例如:

+---------+---------+--------+--------+--------+-------+
| Product | Classif | Type 1 | Type 2 | Type 3 | Price |
+---------+---------+--------+--------+--------+-------+
| a       | Type 1  |      2 |      6 |      8 |     2 |
| b       | Type 2  |      3 |      9 |     11 |     9 |
| c       | Type 3  |      5 |     10 |     15 |    15 |
+---------+---------+--------+--------+--------+-------+

程序在其中比较列classif的值,并从相应列中获取值。

解决方法

这行吗?

library(data.table)

df <- data.table(Product = c('a','b','c'),Classif = c('Type 1','Type 2','Type 3'),`Type 1` = c(2,3,5),`Type 2` = c(6,9,10),`Type 3` = c(8,11,15)
             )


df2 <- df[,`:=`(
  Price = case_when(
     Classif == 'Type 1' ~ `Type 1`,Classif == 'Type 2' ~ `Type 2`,Classif == 'Type 3' ~ `Type 3`
  )
)]
,

您可以找到您想要的东西,首先将数据重整为长,然后计算比较以获得价格,以便将所有价格与left_join()结合在一起。下面是使用tidyverse函数的代码:

library(tidyverse)
#Code
df2 <- df %>% left_join(df %>% pivot_longer(-c(Product,Classif)) %>%
  mutate(Price=ifelse(Classif==name,value,NA)) %>%
  filter(!is.na(Price)) %>% select(-c(name,value)))

输出:

  Product Classif Type 1 Type 2 Type 3 Price
1       a  Type 1      2      6      8     2
2       b  Type 2      3      9     11     9
3       c  Type 3      5     10     15    15

使用了一些数据:

#Data
df <- structure(list(Product = c("a","b","c"),Classif = c("Type 1","Type 2","Type 3"),15)),row.names = c(NA,-3L),class = "data.frame")