r - Convert multiple rows into one row depending on unique values in another column
问题描述
I have two columns in a data frame. Based on the unique ids in column 1, I want to create a new column that has all the values from column 2 corresponding to that unique id in column1 separated by ,.
for example:
col1<-c("x", "y", "x", "z", "x", "z")
col2<-c("NY","UT","CA","SA", "SW", "GR")
col3<-c(1, 5, 7, 4, 7, 2)
df<-data.frame(col1, col2, col3, stringsAsFactors=FALSE)
and I want
col1<-c("x", "y", "z")
col2<-c("NY CA SW", "UT","SA, GR")
df2<-data.frame(col1, col2, stringsAsFactors=FALSE)
解决方案
library(dplyr); library(tidyr)
df %>%
group_by(col1) %>%
summarise(col2 = paste(col2, collapse=" "))
# # A tibble: 3 x 2
# col1 col2
# <chr> <chr>
# 1 x NY CA SW
# 2 y UT
# 3 z SA GR
推荐阅读
- php - 如何在表单输入中自动添加括号和斜杠?
- r - 箱线图未正确显示
- javascript - 尝试在打开时将数据从数据库传递到引导模式。我该怎么做呢?
- python - python中MATLAB中“audioplayer”和“play”的等效命令?
- php - Opcache 只显示特定目录和子目录
- forms - 我的网站在 http 上发布表单,但不在 https 上
- python - 如何使用 ffmpeg 将多个显式图像路径连接到视频
- python - 在重叠和非重叠过程中从 3D 图像中提取 3D 补丁并恢复图像
- r - 使用 rcpp 将 R 函数传递给 C 例程
- import - 将 Amazon txt 数据集导入 Neo4j