gpt4 book ai didi

r - 将值从宽更改为长 : 1) Group_By, 2) Spread/Dcast

转载 作者:行者123 更新时间:2023-12-04 11:54:16 25 4
gpt4 key购买 nike

<分区>

我有一个电话号码的名称列表,我想按名称对其进行分组,然后将它们从长格式转换为宽格式,并在各列中填充电话号码

Name        Phone_Number
John Doe 0123456
John Doe 0123457
John Doe 0123458
Jim Doe 0123459
Jim Doe 0123450
Jane Doe 0123451
Jill Doe 0123457

Name Phone_Number1 Phone_Number2 Phone_Number3
John Doe 0123456 0123457 0123458
Jim Doe 0123459 0123450 NA
Jane Doe 0123451 NA NA
Jill Doe NA NA NA
library(dplyr)
library(tidyr)
library(data.table)

df <- data.frame(Name = c("John Doe", "John Doe", "John Doe", "Jim Doe", "Jim Doe", "Jane Doe", "Jill Doe" ),
Phone_Number = c("0123456", "0123457","0123458", "0123459", "0123450","0123451", NA))

df1 <- data.frame(Name = c("John Doe","Jim Doe", "Jane Doe", "Jill Doe" ),
Phone_Number1 = c("0123456", "0123459", "0123451", NA),
Phone_Number2 = c("0123457", "0123450", NA, NA),
Phone_Number3 = c("0123458", NA, NA, NA))

我已经尝试了一系列排列,但我做错的只是没有点击。我猜这与如何正确指定键/值对有关。我得到的最接近的是下面的代码:

tidyr::传播

  df %>%
group_by(Name) %>%
mutate(id = row_number()) %>%
spread(Name, Phone_Number) %>%
select(-id)

data.table::dcast

 df%>% 
dcast(Name + Phone_Number ~ Phone_Number, value.var = "Phone_Number")

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com