将一列中的信息传播到 R 中的多个
Spread information in one column to multiple in R
我的数据集如下:
df = data.frame("ID" = c("AA","AA","BB","BB"),"OriginID" = c("A1","A","B1","B"),"OriginValue" = c(4,3,8,9))
ID OriginID OriginValue
AA A1 4
AA A 3
BB B1 8
BB B 9
我希望我的输出看起来像
df1 = data.frame("ID" = c("AA","BB"),"OriginID_1" = c("A1","B1"),"OriginValue_1" = c(4,8)
,"OriginID_2" = c("A","B"),"OriginValue_2" = c(3,9))
ID OriginID_1 OriginValue_1 OriginID_2 OriginValue_2
AA A1 4 A 3
BB B1 8 B 9
最好的方法是什么?
谢谢!
我们可以在唯一列标识符后使用 pivot_wider
'ID'
library(dplyr)
library(tidyr)
df %>%
group_by(ID) %>%
mutate(rn = row_number()) %>%
pivot_wider(names_from = rn, values_from = c(OriginID, OriginValue))%>%
select(ID, names(.)[-1][order(readr::parse_number(names(.)[-1]))])
# A tibble: 2 x 5
# Groups: ID [2]
# ID OriginID_1 OriginValue_1 OriginID_2 OriginValue_2
# <fct> <fct> <dbl> <fct> <dbl>
#1 AA A1 4 A 3
#2 BB B1 8 B 9
我的数据集如下:
df = data.frame("ID" = c("AA","AA","BB","BB"),"OriginID" = c("A1","A","B1","B"),"OriginValue" = c(4,3,8,9))
ID OriginID OriginValue
AA A1 4
AA A 3
BB B1 8
BB B 9
我希望我的输出看起来像
df1 = data.frame("ID" = c("AA","BB"),"OriginID_1" = c("A1","B1"),"OriginValue_1" = c(4,8)
,"OriginID_2" = c("A","B"),"OriginValue_2" = c(3,9))
ID OriginID_1 OriginValue_1 OriginID_2 OriginValue_2
AA A1 4 A 3
BB B1 8 B 9
最好的方法是什么?
谢谢!
我们可以在唯一列标识符后使用 pivot_wider
'ID'
library(dplyr)
library(tidyr)
df %>%
group_by(ID) %>%
mutate(rn = row_number()) %>%
pivot_wider(names_from = rn, values_from = c(OriginID, OriginValue))%>%
select(ID, names(.)[-1][order(readr::parse_number(names(.)[-1]))])
# A tibble: 2 x 5
# Groups: ID [2]
# ID OriginID_1 OriginValue_1 OriginID_2 OriginValue_2
# <fct> <fct> <dbl> <fct> <dbl>
#1 AA A1 4 A 3
#2 BB B1 8 B 9