基于列重塑数据框并在 R 中的结果行中用逗号分隔
Reshape dataframe based on a column and separate it by a comma in result rows in R
我想像下面这样重塑数据
data <- data.frame(id=c(1,2,3,4),A=c("a","c","a","b"),B=c("b","a","c","c"))
数据
我想通过根据 id 列和 return 与该数据相关的 id 对数据进行排序来重塑数据。我想要的结果如下:
reshape_data
真的很抱歉,我不知道该怎么做。有人可以帮助或建议我吗?非常感谢。
将数据重塑为长格式,然后根据原始数据集的值恢复为宽格式,paste
id
数字并完成。
data <- data.frame(id=c(1,2,3,4),A=c("a","c","a","b"),B=c("b","a","c","c"))
suppressPackageStartupMessages({
library(dplyr)
library(tidyr)
})
data %>%
pivot_longer(-id) %>%
pivot_wider(
id_cols = value,
names_from = name,
values_from = id,
values_fn = list
) %>%
rowwise() %>%
mutate(A = paste(A, collapse = ","),
B = paste(B, collapse = ","))
#> # A tibble: 3 × 3
#> # Rowwise:
#> value A B
#> <chr> <chr> <chr>
#> 1 a 1,3 2
#> 2 b 4 1
#> 3 c 2 3,4
由 reprex package (v2.0.1)
于 2022-05-28 创建
我想像下面这样重塑数据
data <- data.frame(id=c(1,2,3,4),A=c("a","c","a","b"),B=c("b","a","c","c"))
数据
我想通过根据 id 列和 return 与该数据相关的 id 对数据进行排序来重塑数据。我想要的结果如下:
reshape_data
真的很抱歉,我不知道该怎么做。有人可以帮助或建议我吗?非常感谢。
将数据重塑为长格式,然后根据原始数据集的值恢复为宽格式,paste
id
数字并完成。
data <- data.frame(id=c(1,2,3,4),A=c("a","c","a","b"),B=c("b","a","c","c"))
suppressPackageStartupMessages({
library(dplyr)
library(tidyr)
})
data %>%
pivot_longer(-id) %>%
pivot_wider(
id_cols = value,
names_from = name,
values_from = id,
values_fn = list
) %>%
rowwise() %>%
mutate(A = paste(A, collapse = ","),
B = paste(B, collapse = ","))
#> # A tibble: 3 × 3
#> # Rowwise:
#> value A B
#> <chr> <chr> <chr>
#> 1 a 1,3 2
#> 2 b 4 1
#> 3 c 2 3,4
由 reprex package (v2.0.1)
于 2022-05-28 创建