如何將具有不同行號或行數的向量組合到R中的數據框中。下面是示例。每個矢量有7或9行。 sourceVersion和設備是額外的兩行。我希望這些數據框中包含這些數據,並將其保留爲空或對於7行向量觀察值設置爲NA,如我在下表中所示。R具有不同行長度的組合向量
我想這樣的數據框中的數據。
type sourceName sourceVersion device unit creationDate startDate endDate value
HKQuantityTypeIdentifierFlightsClimbed Ryan Praskievicz iPhone 9.3.2 <<HKDevice: 0x15a4af3f0>, name:iPhone, manufacturer:Apple, model:iPhone, hardware:iPhone8,1, software:9.3.2> count 6/2/2016 12:27 6/2/2016 12:09 6/2/2016 12:09 1
HKQuantityTypeIdentifierStepCount Ryan Praskievicz iPhone count 10/2/2014 8:30 9/24/2014 15:07 9/24/2014 15:07 7
這是我試過的。
library(XML)
xmlstr <- '<?xml version="1.0" encoding="UTF-8"?>
<HealthData locale="en_US">
<ExportDate value="2016-06-02 14:05:23 -0400"/>
<Me HKCharacteristicTypeIdentifierDateOfBirth="" HKCharacteristicTypeIdentifierBiologicalSex="HKBiologicalSexNotSet" HKCharacteristicTypeIdentifierBloodType="HKBloodTypeNotSet" HKCharacteristicTypeIdentifierFitzpatrickSkinType="HKFitzpatrickSkinTypeNotSet"/>
<Record type="HKQuantityTypeIdentifierStepCount" sourceName="Ryan Praskievicz iPhone" unit="count" creationDate="2014-10-02 08:30:17 -0400" startDate="2014-09-24 15:07:06 -0400" endDate="2014-09-24 15:07:11 -0400" value="7"/> <Record type="HKQuantityTypeIdentifierFlightsClimbed" sourceName="Ryan Praskievicz iPhone" sourceVersion="9.3.2" device="<<HKDevice: 0x15a4af3f0>, name:iPhone, manufacturer:Apple, model:iPhone, hardware:iPhone8,1, software:9.3.2>" unit="count" creationDate="2016-06-02 12:27:46 -0400" startDate="2016-06-02 12:09:29 -0400" endDate="2016-06-02 12:09:29 -0400" value="1"/> </HealthData>'
xml <- xmlParse(xmlstr)
recordAttribs <- xpathSApply(doc=xml, path="//HealthData/Record", xmlAttrs)
df <- data.frame(t(recordAttribs))
df
這是我得到的輸出到R控制檯
X1
1 HKQuantityTypeIdentifierStepCount, Ryan Praskievicz iPhone, count, 2014-10-02 08:30:17 -0400, 2014-09-24 15:07:06 -0400, 2014-09-24 15:07:11 -0400, 7
X2
1 HKQuantityTypeIdentifierFlightsClimbed, Ryan Praskievicz iPhone, 9.3.2, <<HKDevice: 0x15a4af3f0>, name:iPhone, manufacturer:Apple, model:iPhone, hardware:iPhone8,1, software:9.3.2>, count, 2016-06-02 12:27:46 -0400, 2016-06-02 12:09:29 -0400, 2016-06-02 12:09:29 -0400, 1
會[這裏](http://webcache.googleusercontent.com/search?q=cache:lPRvnOOSAgoJ:www.inside-r.org/packages/ cran/qpcR/docs/cbind.na +&cd = 4&hl = en&ct = clnk&gl = us)做你想找的事情? –
首先,您嘗試綁定具有不同列數的行,而不是綁定具有不同行數的列。這就是說,你不會,一般有一個列對齊的問題?也就是說,如果一行的列數少於另一行,那麼除非您可以以某種方式從數據中推斷出這些列,否則您怎麼知道哪些列丟失? – aichao
@aichao似乎缺少了相同的兩行 - sourceVersion和device。 – Warner