r - 使用分隔符将一列转换为多列
问题描述
有这样的数据框:
data.frame(id = c(1,2), text = c("Google,Amazon", "Amazon,Yahoo"), stringsAsFactors = FALSE)
# id text
# 1 1 Google,Amazon
# 2 2 Amazon,Yahoo
如何使用逗号作为分隔符从文本列创建。预期输出示例:
data.frame(id = c(1,2), Google = c(1,0), Amazon = c(1,1), Yahoo = c(0,1))
# id Google Amazon Yahoo
# 1 1 1 1 0
# 2 2 0 1 1
解决方案
使用库dplyr
和tidyr
library(dplyr)
library(tidyr)
df %>%
mutate(
text = strsplit(text, ","),
value = 1
) %>%
unnest(text) %>%
pivot_wider(
id_cols = id,
names_from = text,
values_from = value,
values_fill = list(value = 0)
)
输出
# A tibble: 2 x 4
# id Google Amazon Yahoo
# <dbl> <dbl> <dbl> <dbl>
# 1 1 1 1 0
# 2 2 0 1 1
推荐阅读
- reactjs - 很多不必要的请求
- c# - 进程“C:\hostedtoolcache\windows\dotnet\dotnet.exe”失败,退出代码为 1
- javascript - JSON 结果值作为 JavaScript/jQuery 中的键
- wpf - 如何根据输入文本过滤组合框项目?
- awk - awk 匹配正则表达式警告
- java - Realm Android 无法解析符号“SyncUser”
- yolo - 错误:在文件 data/coco.names 中的名称数 80 不等于 classes=13
- javascript - 如何添加实际有效的自定义反应?
- javascript - 动态角度注入服务
- permissions - 如何将 Linux (Android) ARM64 可执行文件分成小部分和大部分?