简体   繁体   English

在 R 中使用 tidyverse 如何以固定方式排列我的列值?

[英]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 更改为 "a,b,c" 命令

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.它不是将 'id' 列分配给data <- (这将用 'id' 值替换数据),而是用于order In base R , this can be done withbase R ,这可以通过

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

Or with dplyr或者用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或在基础 R

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

暂无
暂无

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

相关问题 使用 tidyverse 和管道如何分配固定行 - Using tidyverse and pipes how do I assign fixed rows 如何以“tidyverse”方式按名称在 R 中重新编码多个列? - How do I recode several columns by name in R in a "tidyverse" way? 如何根据不同列中的值重新编码 R tidyverse 中的值 - How to recode values in R tidyverse based on the values in a different column 如何使用 mutate - tidyverse/dplyr 通过 sys.Date() 减去一列日期值? 电阻 - How to subtract a column of date values by sys.Date() using mutate - tidyverse/dplyr? R 如何将行名添加到分组数据框中的列(R,tidyverse) - How can I add rownames to a column in a grouped dataframe (R, tidyverse) 如何使用 Tidyverse 在 R 中聚合混乱的季度数据,搜索第一个连续的四个季度集 - How do I aggregate messy quarterly data in R using Tidyverse, searching for first contiguous set of four quarters 如何在 R 中使用 tidyverse 并行汇总和绑定大型数据集? - How do I summarise and bind large data sets in parallel using tidyverse in R? 如何使用R中的tidyverse按组创建一个变量的值组合 - How to create combinations of values of one variable by group using tidyverse in R 如何使用 R 对不同列中重复键的字符串值进行排列、分组和集中 - How to arrange, group and concentrate string values of repeated keys in different column using R 如何使用 tidyverse 语法将列名从 dataframe 传递到 function 中? - How do I pass a column name from a dataframe into a function using tidyverse syntax?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM