简体   繁体   中英

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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