简体   繁体   English

如何将行名添加到分组数据框中的列(R,tidyverse)

[英]How can I add rownames to a column in a grouped dataframe (R, tidyverse)

I would like to add the rownames of my dataframe to a new column within my dataframe.我想将数据框的行名添加到数据框中的新列中。 But not for the whole dataframe, but for the grouped dataframe.但不是针对整个数据帧,而是针对分组数据帧。 The idea is, to have ascending rownames for each subject and within each subject, for each trial.这个想法是,对于每个试验,每个主题和每个主题内都有升序的行名。 I tried it the following way without success:我尝试了以下方法但没有成功:

library(tidyverse)
df <- as_tibble(iris) %>% 
  arrange(Species, Petal.Width)

df <- df %>%
  group_by(Species, Petal.Width) %>% 
  mutate(rowname = rownames_to_column())```

So, in the end, this code does what I was aiming for:所以,最后,这段代码完成了我的目标:

library(tidyverse) 

df <- as_tibble(iris) %>% arrange(Species, Petal.Width)

df <- df %>%   group_by(Species, Petal.Width) %>% mutate(rowname = row_number() - 1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM