データ(xlsxファイル)を正しい形式で取得するのに苦労しています。私の元のデータベースは次のとおりです。
patient when age weight height watchID dateFrom
<chr> <chr> <dbl> <dbl> <dbl> <dbl> <dttm>
1 T01 pre 82 83 174 2788 2017-07-24
2 T02 pre 81 80 166 7309 2017-07-22
3 T02 post 67 91 163 7309 2017-10-26
4 T03 pre 68 91 172 5066 2017-07-26
5 T03 post 68 91 172 7220 2017-10-24
「when」列に基づいて患者IDが1つしかない幅広いデータベースを取得したいと思います。しかし、私がそれを再形成しようとすると、私はついに「dcast」関数でこれに到達します。
patient age_post age_pre weight_post weight_pre height_post height_pre
<chr> <int> <int> <int> <int> <int> <int>
1 T01 0 1 0 1 0 1
2 T02 1 1 1 1 1 1
3 T03 1 1 1 1 1 1
4 T04 0 1 0 1 0 1
5 T05 1 0 1 0 1 0
どういうわけか、すべての変数を1と0に変更します。元の列に「pre」と「post」が付加された、異なる変数タイプの同様のデータベースを取得するにはどうすればよいですか。
これは私のコードです(「HW」は上記の元のデータセットです):
mdata <- melt(HW, id=c("patient","when"))
mdata$value <- as.numeric(as.character(mdata$value)) #I added this line to convert the column to numeric but it doesn't help
mdata2 <- dcast(mdata, patient~variable+when)
私もそれを試しました:
mdata <- melt(HW, id=c("patient","when"))
mdata3 <- reshape(mdata, idvar='patient', timevar='when', direction='wide')
しかし、私はこれを取得します:
patient variable.pre value.pre variable.post value.post
<chr> <fct> <chr> <fct> <chr>
1 T01 age 82 NA NA
2 T02 age 81 age 67
3 T03 age 68 age 68
4 T04 age 81 NA NA
5 T05 NA NA age 87
他の変数なし。
前もって感謝します。
これはあなたが望むことをしますか?
library(tidyr)
df <- tibble(patient = c("T01","T02","T02","T03","T03"),
when = c("pre","pre","post","pre","post"),
age = c(82,81,67,68,68),
weight = c(83,80,91,91,91),
height = c(174,166,163,172,172),
watchid = c(2788,7309,7309,5066,7220),
datefrom = c("2017-07-24","2017-07-22","2017-10-26",
"2017-07-26","2017-10-24"))
df %>%
pivot_wider(names_from = when,
values_from = c(age,weight,height,watchid,datefrom))
A tibble: 3 x 11
patient age_pre age_post weight_pre weight_post height_pre height_post watchid_pre watchid_post
<chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 T01 82 NA 83 NA 174 NA 2788 NA
2 T02 81 67 80 91 166 163 7309 7309
3 T03 68 68 91 91 172 172 5066 7220
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加