我有一个带有2列的data.frame df,前六行显示在这里,但是它有更多的阻塞序列,每行包含3行:
blocksequenceid description
M049-S215-S085 ECDTM-49
M049-S215-S085 ICD-215
M049-S215-S085 ICD-85
M049-S213-S044 ECDTM-49
M049-S213-S044 ICD-213
M049-S213-S044 ICD-44
我想将其转换为以下格式:
blocksequenceid description1 description2 description3
M049-S215-S085 ECDTM-49 ICD-215 ICD-85
M049-S213-S044 ECDTM-49 ICD-213 ICD-44
我已经考虑了dcast和reshape,但是当我说ERROR: column time not found
进行重塑时我不知道该怎么做,我不确定dcast是否适合在这里使用。这就是我尝试过的:
reshape(df, idvar='blocksequenceid', timevar = 'description', direction = 'wide')
reshape(df, idvar='blocksequenceid', v.names = 'description', direction = 'wide')
我确信这很简单,但我只缺少一些东西。
答案 0 :(得分:2)
这是可重复的数据。
t <- 'blocksequenceid description
M049-S215-S085 ECDTM-49
M049-S215-S085 ICD-215
M049-S215-S085 ICD-85'
df <- read.table(text = t, header = T)
这是一个可能的解决方案。
library(tidyverse)
df %>%
rename(description1 = description) %>%
mutate(description = row_number()) %>%
spread(description, description1, sep = "")
# blocksequenceid description1 description2 description3
# 1 M049-S215-S085 ECDTM-49 ICD-215 ICD-85
t <- 'blocksequenceid description
M049-S215-S085 ECDTM-49
M049-S215-S085 ICD-215
M049-S215-S085 ICD-85
M049-S213-S044 ECDTM-49
M049-S213-S044 ICD-213
M049-S213-S044 ICD-44'
df <- read.table(text = t, header = T)
在更新的数据中,您应该先group_by(blocksequenceid)
。
library(tidyverse)
df %>%
rename(description1 = description) %>%
group_by(blocksequenceid) %>%
mutate(description = row_number()) %>%
spread(description, description1, sep = "")
# # A tibble: 2 x 4
# # Groups: blocksequenceid [2]
# blocksequenceid description1 description2 description3
# <chr> <chr> <chr> <chr>
# 1 M049-S213-S044 ECDTM-49 ICD-213 ICD-44
# 2 M049-S215-S085 ECDTM-49 ICD-215 ICD-85