gpt4 book ai didi

r - 将 data.frame 转换为单行

转载 作者:行者123 更新时间:2023-12-02 12:22:51 24 4
gpt4 key购买 nike

我有这些数据:

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.countjournal.rank ...最快的方法是什么?由于某种原因,dcastreshape 没有为我做这件事,我的解决方案有点太麻烦了。

最佳答案

您提到了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

不过,类型和变量是用_分隔的,而不是.

关于r - 将 data.frame 转换为单行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12647159/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com