首页 > 解决方案 > 如何根据字母顺序重新排列数据框每一行中的条目(字符)?

问题描述

我有一个data.frame这样的:

df=data.frame(word1 = c("hello", "red", "red"), word2 = c("world", "hello", "yellow"), word3 = 
                   c("red", "world", "hello"), n = c(574L, 306L, 302L))

IE

> df
  word1  word2 word3   n
1 hello  world   red 574
2   red  hello world 306
3   red yellow hello 302

我想根据字母顺序重新排列每行中的单词。例如:

> df_new
  word1 word2 word3    n
1 hello   red world  574
2 hello   red world  306
3 hello   red yellow 302

标签: rstringdataframe

解决方案


Loop over the rows with apply on the selected column, sort and update those columns

df[1:3] <- t(apply(df[1:3], 1, sort))

Or using dplyr/tidyr

library(dplyr)
library(tidyr)
df %>% 
   rowwise %>% 
   transmute(out = list(sort(c_across(where(is.character)))), n) %>% 
   ungroup %>%
   unnest_wider(c(out), names_repair =  ~names(df))

推荐阅读