英文:
How to merge a specific column with each column of a dataframe?
问题
让我们假设我有这个数据框(我的原始数据框要大得多):
df = data.frame(ID = c(1,2,2,3,4,5,5),
T = c(1,1,2,1,2,1,2),
product_1 = c('A','A','B','C','A','C','D'),
product_2 = c('C','A','B','A','B','E','C')
)
我希望得到以下输出:
ID product_1_T1 product_1_T2 product_2_T1 product_2_T2
1 1 A <NA> C <NA>
2 2 A B A B
3 3 C <NA> A <NA>
4 4 <NA> A <NA> B
5 5 C D E C
如果你有任何其他问题,请随时提出。
英文:
Let's say I have this df (my original dataframe is so much bigger)
df = data.frame(ID = c(1,2,2,3,4,5,5),
T = c(1,1,2,1,2,1,2),
product_1 = c('A','A','B','C','A','C','D'),
product_2 = c('C','A','B','A','B','E','C'),
)
I wish to have the following output
ID product_1_T1 product_1_T2 product_2_T1 product_2_T2
1 1 A <NA> C <NA>
2 2 A B A B
3 3 C <NA> A <NA>
4 4 <NA> A <NA> B
5 5 C D E C
>
````
</details>
# 答案1
**得分**: 1
```r
使用 `pivot_wider` 函数:
```r
library(tidyr)
pivot_wider(df, names_from = 'T', values_from = product_1:product_2, names_prefix = "T")
```
# 生成的数据表:
# 5 行 × 5 列
ID product_1_T1 product_1_T2 product_2_T1 product_2_T2
<dbl> <chr> <chr> <chr> <chr>
1 1 A NA C NA
2 2 A B A B
3 3 C NA A NA
4 4 NA A NA B
5 5 C D E C
```
<details>
<summary>英文:</summary>
With `pivot_wider`:
```r
library(tidyr)
pivot_wider(df, names_from = 'T', values_from = product_1:product_2, names_prefix = "T")
# A tibble: 5 × 5
ID product_1_T1 product_1_T2 product_2_T1 product_2_T2
<dbl> <chr> <chr> <chr> <chr>
1 1 A NA C NA
2 2 A B A B
3 3 C NA A NA
4 4 NA A NA B
5 5 C D E C
```
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论