我有这些数据:
structure(list(type = c("journal", "all", "similar_age_1m", "similar_age_3m",
"similar_age_journal_1m", "similar_age_journal_3m"), count = c("13972",
"754555", "22408", "56213", "508", "1035"), rank = c("13759",
"754043", "22339", "56074", "459", "947"), pct = c("98.48", "99.93",
"99.69", "99.75", "90.35", "91.50")), .Names = c("type", "count",
"rank", "pct"), row.names = c(NA, -6L), class = "data.frame")
我想将其变成一行,并以相应类型作为前缀的
2:4
列名称。例如journal.count
,journal.rank
...最快的方法是什么?由于某种原因,dcast
和reshape
对我而言不起作用,我的解决方案太麻烦了。 最佳答案
您提到了reshape2
,所以这是一种解决方法:
library("reshape2")
dcast(melt(dat, id.var="type"), 1~variable+type)
这给出了:
1 count_all count_journal count_similar_age_1m count_similar_age_3m
1 1 754555 13972 22408 56213
count_similar_age_journal_1m count_similar_age_journal_3m rank_all
1 508 1035 754043
rank_journal rank_similar_age_1m rank_similar_age_3m
1 13759 22339 56074
rank_similar_age_journal_1m rank_similar_age_journal_3m pct_all pct_journal
1 459 947 99.93 98.48
pct_similar_age_1m pct_similar_age_3m pct_similar_age_journal_1m
1 99.69 99.75 90.35
pct_similar_age_journal_3m
1 91.50
type
和变量用_
代替,而不是.
。关于r - 将data.frame变成一行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12647159/