我想以一种方式重塑我的数据,使得与另一列相关的一列中的区域值显示在新创建的列中
df
A B
1 <NA> <NA>
2 a b
3 a d
4 b c
相近 :
> df %>%
+ group_by(A) %>%
+ summarise(n_distinct(B))
# A tibble: 3 x 2
A `n_distinct(B)`
<chr> <int>
1 a 2
2 b 1
3 NA 1
但是,不是计算出现次数,只需在新列中显示实际值?
如下所示:
df
A B
1 <NA> <NA>
2 a b **d**
4 b c
我尝试传播,但它不起作用,出现以下错误:
错误:行的重复标识符
我的列都是因子,但如果需要可以重新分类。
谢谢!
library(dplyr)
library(tidyr)
df %>% group_by(A) %>% summarise(B=paste0(unique(B), collapse = ',')) %>%
separate(B,into = paste0('B',1:2))
# A tibble: 3 x 3
A B1 B2
<chr> <chr> <chr>
1 a b d
2 b c NA
3 NA NA NA
Warning message:
Expected 2 pieces. Missing pieces filled with `NA` in 2 rows [2, 3].
这是在创建序列列后使用spread
的选项
library(tidyverse)
df %>%
group_by(A) %>%
mutate(n1 = paste0("B", row_number())) %>%
ungroup %>%
spread(n1, B)
# A tibble: 3 x 3
# A B1 B2
# <fct> <fct> <fct>
#1 a b d
#2 b c <NA>
#3 <NA> <NA> <NA>
df <- data.frame(A = c(NA, 'a', 'a', 'b'), B = c(NA, 'b', 'd', 'c'))