r - 有没有办法转置不同的列名
问题描述
有没有办法用不同的列名转置数据框例如
Col A Col B
Table1 Date
Table1 Country
Table2 Name
Table2 Date
Table3 ID
Table3 Place
必需的输出(同名的列应在同一列中对齐,如日期)
Col A Col1 Col2 Col3
Table1 Date Country
Table2 Date Name
Table3 ID Place
解决方案
似乎要获得所需的输出,您必须解决存在 > 1 个ColB
值实例的情况以及分别只有 1 个实例的情况。
选项1:
library(data.table)
setDT(df)
df[, single := .N == 1L, ColB]
df[, b_id := frank(ColB, ties.method = 'dense')]
out <-
merge(
dcast(df[single == F], ColA ~ b_id, value.var = 'ColB'),
dcast(df[single == T], ColA ~ rowid(ColA), value.var = 'ColB'),
by = 'ColA',
all = T
)
setnames(out, replace(paste0('Col', seq(0, ncol(out) - 1)), 1, names(out)[1]))
out
# ColA Col1 Col2 Col3
# 1: Table1 Date Country <NA>
# 2: Table2 Date Name <NA>
# 3: Table3 <NA> ID Place
选项 2:
library(data.table)
setDT(df)
df[, single := .N == 1L, ColB]
df[, b_id :=
interaction(single, fifelse(single, rowid(ColA), frank(ColB, ties.method = 'dense')))]
dcast(df, ColA ~ paste0('Col', as.integer(b_id)), value.var = 'ColB')
# ColA Col2 Col3 Col4
# 1: Table1 <NA> Date Country
# 2: Table2 Name Date <NA>
# 3: Table3 ID <NA> Place
输入数据:
df <- fread('
ColA ColB
Table1 Date
Table1 Country
Table2 Name
Table2 Date
Table3 ID
Table3 Place
')
推荐阅读
- java - 远程休息 api 更改时运行 postconstruct 注释方法
- mongodb - 如何从以特定文本开头且仅以 mongodb 中的数字结尾的条目中获取数字数组?
- python - 从视频中捕获图像后将图像上传到s3
- wordpress - 如何在图库中查看网站模板?
- ckeditor - CKEditor 4 - cannot replace selection
- c# - 如何从 IIS 绑定中获取 IP 地址
- angular - 输入 url 时 canActivate 不起作用
- c# - 创建等待任务以发送消息
- javascript - 时刻js添加功能不起作用
- r - 如何使用 project-lib 将 csv 文件保存到云对象存储?