r - 转置数据帧
问题描述
有我遇到的情况
> sample_df <- data.frame(id = c(14129, 29102, 2191, 2192, 1912)
, color = c("blue", "red", "green", "purple", "blue")
, day = c("monday", "wednesday", "thursday", "monday", "tuesday")
, happy = c(1, 1, 1, 1, 1))
> sample_df
id color day happy
14129 blue monday 1
29102 red wednesday 1
2191 green thursday 1
2192 purple monday 1
1912 blue tuesday 1
希望能够创建一个将两列转置为具有以下内容的列:
> sample_df_2 <- data.frame(id = c(14129,14129, 29102,29102, 2191,2191, 2192,2192, 1912,1912)
, type = c("blue", "monday","red","wednesday","green","thursday","purple","monday","blue","tuesday")
, happy = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1))
> sample_df_2
id type happy
14129 blue 0
14129 monday 1
29102 red 0
29102 wednesday 1
2191 green 0
2191 thursday 1
2192 purple 0
2192 monday 1
1912 blue 0
1912 tuesday 1
关于最后一列的想法只是说,如果我们正在处理从原始color
字段中提取的值,happy
则为自动0
,否则1
解决方案
输入“long”格式后gather
,一种选择是将“key”列中与“color”对应的“happy”中的值替换为否定值、select
感兴趣的列以及arrange
必要时
library(tidyverse)
gather(sample_df, key, type, color:day) %>%
mutate(happy = case_when(key == "color" ~ as.numeric(!happy), TRUE ~ happy)) %>%
select(-key) %>%
arrange(id)
推荐阅读
- python - 在 python 中绘制两个数组,其中一个填充随机数
- python - 在 GCP 上的哪里存储我的自定义 Python 模块,以便不同的 GCP 服务可以访问它们?
- python - 错误 SSL | Python 3.8 请帮帮我谢谢
- node.js - 从我的 reactjs 应用程序向我的 express 服务器发送请求时出现 CORS 错误,该服务器重定向到 Spotify 的 API
- r - 为什么人们会在 apARCH、gjrGARCH 和 E-GARCH 之间进行选择,是否有任何关键原因?
- angular - 如何在 Angular component.ts 中的函数之外声明 HTMLElement 变量?
- mongodb - 与 go-driver 相比,mongodb-rust-driver 在查找和获取大量数据时表现不佳
- c# - 如何以编程方式访问 AWS 开发工具包使用的 AWS 凭证?
- python - 不能使 folder_path = filedialog.askdirectory() 全局
- python - 如何将列表写入文件?