用时间不变变量的一些缺失数据(NA;s)从长到宽重塑 [英] Reshaping from long to wide with some missing data (NA's) on time invariant variables

查看:10
本文介绍了用时间不变变量的一些缺失数据(NA;s)从长到宽重塑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用stats:::reshape()from base将数据从长格式转换为宽格式时,对于指定为时间不变的任何变量,reshape只取第一个观察值,如果变量实际上以某种方式变化,则输出警告。在我的例子中,我有关于我想指定为时间不变量的变量的缺失数据,但由于我在其他时间点有此数据,我希望使用这些时间点的值,而不是首先观察到的NA

testdata <- data.frame(matrix(c(1,1,2,3,4,3.5,NA,6,4,1,2,1), nrow = 3))
colnames(testdata) <- c("id", "process1", "timeinvariant", "time")
# > testdata
#   id process1 timeinvariant time
# 1  1      3.0            NA    1
# 2  1      4.0             6    2
# 3  2      3.5             4    1

# Note here the missing data on the invariant process at time 1
reshaped <- reshape(testdata, v.names="process1", direction = "wide")
# > reshaped
#   id timeinvariant process1.1 process1.2
# 1  1            NA        3.0          4
# 3  2             4        3.5         NA

NA按比例分配到宽格式,而我宁愿采用在时间2(或任何时候)观察到的值。

推荐答案

我不知道如何修复该问题,但修复症状的一种方法是按顺序降低NA值。

testdata <- testdata[order(testdata$timeinvariant),]
testdata
#  id process1 timeinvariant time
#3  2      3.5             4    1
#2  1      4.0             6    2
#1  1      3.0            NA    1
reshaped<-reshape(testdata,v.names="process1",direction="wide")
reshaped
#  id timeinvariant process1.1 process1.2
#3  2             4        3.5         NA
#2  1             6        3.0          4

更一般的解决方案是确保每个ID的TimeVariable列中只有一个值

testdata$timeinvariant <- apply(testdata,1,function(x) max(testdata[testdata$id == x[1],"timeinvariant"],na.rm=T))
testdata
#  id process1 timeinvariant time
#3  2      3.5             4    1
#2  1      4.0             6    2
#1  1      3.0             6    1
在调用重塑函数之前,可以对任意数量的列重复此操作。 希望这能有所帮助

这篇关于用时间不变变量的一些缺失数据(NA;s)从长到宽重塑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆