r - 如何根据字母顺序重新排列数据框每一行中的条目(字符)?
问题描述
我有一个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
解决方案
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))
推荐阅读
- sql-server - SQL 使用来自多个链接表的子查询获取计数
- android - 如何在小部件上禁用多点触控。扑
- c++ - Qt:父子小部件。关闭单个子部件是否意味着关闭其他子部件?
- graphviz - Graphviz 水平对齐顶部/底部的节点
- sql - 将查询返回的数字列表存储到变量中
- php - composer require 不适用于 git bash(Wamp)
- celery - Celery 任务代码是否需要存在于多台机器上?
- arrays - 我是否将传入数据列为复选框?
- android - 是否可以使用相同模型的 JSONObject 和 RealmObject 进行解析?
- javascript - 使用 jasmine marbles 时在 rxjs 订阅中测试代码