简体   繁体   中英

Using tidyverse in R how do I arrange my column values in a fixed way?

ID score
a  1
a  2
b  2
b  4
c  4
c  5

I want to change id to "a,b,c" order this to

ID score
a  1
b  2
c  4
a  2
b  4
c  5

What I tried

> data <- read_csv(data)
> data <- factor(data$id, levels = c('a', 'b', 'c'))

This works for tables so I tried it but didn't work for this. Anybody know if there is a way?

Instead of assigning the 'id' column to data <- (which would replace the data with the 'id' values) it would be used for order ing. In base R , this can be done with

data1 <-  data[order(duplicated(data$ID)),]
row.name(data1) <- NULL

Or with dplyr

library(dplyr)
library(data.table)
data %>%
     arrange(rowid(ID))
library(dplyr)
d %>%
    group_by(ID) %>%
    mutate(r = row_number()) %>%
    ungroup() %>%
    arrange(r, ID, score) %>%
    select(-r)

OR in base R

with(d, d[order(ave(seq(NROW(d)), d$ID, FUN = seq_along), ID, score),])

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