需要让列显示哪些 ID 分配给这些列......不知道如何描述
Need to make columns showing which IDs are assigned to those columns...not sure how to describe
每个病人被分配给两个医生。一共有三个医生。我的数据如下所示:
>df
Dr1 Dr2 PatientID
Chris John 5
John Mike 24
Mike John 28
我想要的是 3 列(每个医生一列)显示他们的病人是谁
Chris John Mike
5 5 24
24 28
28
我正在尝试玩 melt()
但运气不好。
创建具有参差不齐的列(即不同长度的列)的数据框有点棘手,但这是一个尝试。注意 magrittr 的 %$%
运算符的使用:
library(tidyverse)
df <- read.table(text = 'Dr1 Dr2 PatientID
Chris John 5
John Mike 24
Mike John 28', header = T)
list.per.dr <- df %>%
gather(doc, name, -PatientID) %>%
select(-doc) %$%
split(PatientID, name)
$Chris
[1] 5
$John
[1] 24 5 28
$Mike
[1] 28 24
我们现在有一个列表对象,它给出了分配给每位医生的患者。要将其转换为数据框,我们需要使它们的长度相等:
max_patients <- max(lengths(list.per.dr))
df.new <- list.per.dr %>%
lapply(function(x) c(x, rep(NA, max_patients - length(x)))) %>%
as.data.frame()
Chris John Mike
1 5 24 28
2 NA 5 24
3 NA 28 NA
数据框是矩形的。你想要的不是矩形,所以让我们制作一个 list
代替:
with(reshape2::melt(df, id.vars = "PatientID"), split(PatientID, value))
# $Chris
# [1] 5
#
# $John
# [1] 24 5 28
#
# $Mike
# [1] 28 24
使用此数据:
df = read.table(text = "Dr1 Dr2 PatientID
Chris John 5
John Mike 24
Mike John 28", header = T)
类似于 Gregor 解决方案的基本 R 选项
unstack(reshape(dat, idvar = "PatientID", varying = 1:2, direction = "long", sep = ""),
PatientID ~ Dr)
# $Chris
# [1] 5
#
# $John
# [1] 24 5 28
#
# $Mike
# [1] 28 24
数据
text <- "Dr1 Dr2 PatientID
Chris John 5
John Mike 24
Mike John 28"
dat <- read.table(text = text, stringsAsFactors = FALSE, header = TRUE)
每个病人被分配给两个医生。一共有三个医生。我的数据如下所示:
>df
Dr1 Dr2 PatientID
Chris John 5
John Mike 24
Mike John 28
我想要的是 3 列(每个医生一列)显示他们的病人是谁
Chris John Mike
5 5 24
24 28
28
我正在尝试玩 melt()
但运气不好。
创建具有参差不齐的列(即不同长度的列)的数据框有点棘手,但这是一个尝试。注意 magrittr 的 %$%
运算符的使用:
library(tidyverse)
df <- read.table(text = 'Dr1 Dr2 PatientID
Chris John 5
John Mike 24
Mike John 28', header = T)
list.per.dr <- df %>%
gather(doc, name, -PatientID) %>%
select(-doc) %$%
split(PatientID, name)
$Chris
[1] 5
$John
[1] 24 5 28
$Mike
[1] 28 24
我们现在有一个列表对象,它给出了分配给每位医生的患者。要将其转换为数据框,我们需要使它们的长度相等:
max_patients <- max(lengths(list.per.dr))
df.new <- list.per.dr %>%
lapply(function(x) c(x, rep(NA, max_patients - length(x)))) %>%
as.data.frame()
Chris John Mike
1 5 24 28
2 NA 5 24
3 NA 28 NA
数据框是矩形的。你想要的不是矩形,所以让我们制作一个 list
代替:
with(reshape2::melt(df, id.vars = "PatientID"), split(PatientID, value))
# $Chris
# [1] 5
#
# $John
# [1] 24 5 28
#
# $Mike
# [1] 28 24
使用此数据:
df = read.table(text = "Dr1 Dr2 PatientID
Chris John 5
John Mike 24
Mike John 28", header = T)
类似于 Gregor 解决方案的基本 R 选项
unstack(reshape(dat, idvar = "PatientID", varying = 1:2, direction = "long", sep = ""),
PatientID ~ Dr)
# $Chris
# [1] 5
#
# $John
# [1] 24 5 28
#
# $Mike
# [1] 28 24
数据
text <- "Dr1 Dr2 PatientID
Chris John 5
John Mike 24
Mike John 28"
dat <- read.table(text = text, stringsAsFactors = FALSE, header = TRUE)