0

我有一张桌子,比如

+---------+---------+--------+--------+--------+
| 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的值,并从相应列中获取值。

4

2 回答 2

1

这行得通吗?

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`
  )
)]
于 2020-09-30T13:56:25.197 回答
1

您可以先将您的数据重新整形为 long,然后计算比较以获得价格,以便将所有数据连接在一起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"), `Type 1` = c(2, 3, 5), `Type 2` = c(6, 9, 
10), `Type 3` = c(8, 11, 15)), row.names = c(NA, -3L), class = "data.frame")
于 2020-09-30T13:59:00.917 回答