gpt4 book ai didi

r - 如何传播具有重复标识符的列?

转载 作者:行者123 更新时间:2023-12-03 07:26:32 25 4
gpt4 key购买 nike

A 有以下小标题:

structure(list(age = c("21", "17", "32", "29", "15"), 
gender = structure(c(2L, 1L, 1L, 2L, 2L), .Label = c("Female", "Male"), class = "factor")),
row.names = c(NA, -5L), class = c("tbl_df", "tbl", "data.frame"), .Names = c("age", "gender"))

age gender
<chr> <fctr>
1 21 Male
2 17 Female
3 32 Female
4 29 Male
5 15 Male

我正在尝试使用 tidyr::spread为达到这个:
  Female Male
1 NA 21
2 17 NA
3 32 NA
4 NA 29
5 NA 15

我以为 spread(gender, age)会工作,但我收到一条错误消息:

Error: Duplicate identifiers for rows (2, 3), (1, 4, 5)

最佳答案

现在你有两个 age Female 的值三个用于 Male ,并且没有其他变量阻止它们被折叠成一行,如 spread尝试处理具有相似/无索引值的值:

library(tidyverse)

df <- data_frame(x = c('a', 'b'), y = 1:2)

df # 2 rows...
#> # A tibble: 2 x 2
#> x y
#> <chr> <int>
#> 1 a 1
#> 2 b 2

df %>% spread(x, y) # ...become one if there's only one value for each.
#> # A tibble: 1 x 2
#> a b
#> * <int> <int>
#> 1 1 2
spread不应用函数来组合多个值(à la dcast ),因此必须对行进行索引,以便一个位置有一个或零值,例如

df <- data_frame(i = c(1, 1, 2, 2, 3, 3), 
x = c('a', 'b', 'a', 'b', 'a', 'b'),
y = 1:6)

df # the two rows with each `i` value here...
#> # A tibble: 6 x 3
#> i x y
#> <dbl> <chr> <int>
#> 1 1 a 1
#> 2 1 b 2
#> 3 2 a 3
#> 4 2 b 4
#> 5 3 a 5
#> 6 3 b 6

df %>% spread(x, y) # ...become one row here.
#> # A tibble: 3 x 3
#> i a b
#> * <dbl> <int> <int>
#> 1 1 1 2
#> 2 2 3 4
#> 3 3 5 6

如果您的值没有被其他列自然索引,您可以添加一个唯一索引列(例如,通过将行号添加为列)这将停止 spread从试图折叠行:

df <- structure(list(age = c("21", "17", "32", "29", "15"), 
gender = structure(c(2L, 1L, 1L, 2L, 2L),
.Label = c("Female", "Male"), class = "factor")),
row.names = c(NA, -5L),
class = c("tbl_df", "tbl", "data.frame"),
.Names = c("age", "gender"))

df %>% mutate(i = row_number()) %>% spread(gender, age)
#> # A tibble: 5 x 3
#> i Female Male
#> * <int> <chr> <chr>
#> 1 1 <NA> 21
#> 2 2 17 <NA>
#> 3 3 32 <NA>
#> 4 4 <NA> 29
#> 5 5 <NA> 15

如果您以后想删除它,请添加 select(-i) .在这种情况下,这不会产生非常有用的 data.frame,但在更复杂的 reshape 过程中可能非常有用。

关于r - 如何传播具有重复标识符的列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45898614/

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