![](/img/trans.png)
[英]How can I add rownames to a column in a grouped dataframe (R, tidyverse)
[英]How can I get lists of rownames as values after aggregating a dataframe?
我有一個像這樣的數據幀:
type V1 V2
1 A bla bla
2 A bla bla
3 B bloo bla
4 B bloo bla
5 C moo bloo
6 C moo bloo
目前我融化/施法得到這個:
type bla bloo moo
A 4 0 0
B 2 2 0
C 0 2 2
使用這些命令:
library(reshape)
melted <- melt(df, id='type')
count <- function(x) {
length(na.omit(x))
}
casted <- cast(melted, type~value, count)
然而,我想獲得原始rownames的列表而不是計數/求和。 像這樣的東西:
type bla bloo moo
A 1,2 0 0
B 3,4 3,4 0
C 0 5,6 5,6
其中bla,bloo和moo的每個值都是原始數據框中唯一的rownames列表。
有人可以幫忙嗎?
library(reshape2)
df <- read.table(text="type V1 V2
1 A bla bla
2 A bla bla
3 B bloo bla
4 B bloo bla
5 C moo bloo
6 C moo bloo")
df$id <- rownames(df)
melted <- melt(df, id=c('type','id'),measure.vars=c("V1","V2"))
fun <- function(x) paste(unique(x),collapse=",")
dcast(melted,type~value,fun,value.var="id",fill="0")
# type bla bloo moo
#1 A 1,2 0 0
#2 B 3,4 3,4 0
#3 C 0 5,6 5,6
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.