一种选择是
apply
函数并为最后3列传递行数据。好的一面
应用
行数据是否作为
named-vector
哪里
name
与列名称匹配。
现在,必须先合并
名称
具有
value
使用
paste
然后使用
collapse=";"
函数论元
paste0
. 解决方案如下:
cbind(df[1:4],Attribute =
apply(df[,5:7],1, function(x)paste0(paste(names(x[!is.na(x)]),x[!is.na(x)], sep = "="),
collapse = ";")))
# ID Event.Category Start.Time End.Time Attribute
# 1 1 Stroke 1/1/2011 <NA>
# 2 1 Admitted 1/6/2011 <NA> Account.No.=24287939;Doctor.s_ID=5487
# 3 1 Diagnosed 1/25/2011 <NA>
# 4 6 Diagnosed 1/1/2011 <NA>
# 5 6 Drug A 1/2/2011 1/10/2011 Dosage=high
# 6 6 Drug B 1/7/2011 1/20/2011 Account.No.=35287930;Dosage=medium
# 7 10 Drug A 1/3/2011 1/6/2011 Dosage=low
# 8 10 Drug B 1/9/2011 1/13/2011 Dosage=high
# 9 10 Stroke 1/8/2011 <NA>
数据:
df <- read.table(text =
'ID "Event Category" "Start Time" "End Time" "Account No." Dosage Doctor\'s_ID
1 Stroke 1/1/2011 NA NA NA NA
1 Admitted 1/6/2011 NA 24287939 NA 5487
1 Diagnosed 1/25/2011 NA NA NA NA
6 Diagnosed 1/1/2011 NA NA NA NA
6 "Drug A" 1/2/2011 1/10/2011 NA "high" NA
6 "Drug B" 1/7/2011 1/20/2011 35287930 "medium" NA
10 "Drug A" 1/3/2011 1/6/2011 NA "low" NA
10 "Drug B" 1/9/2011 1/13/2011 NA "high" NA
10 Stroke 1/8/2011 NA NA NA NA',
stringsAsFactors = FALSE, header = TRUE)