r - pivot_wider:如何为非唯一值添加行?
问题描述
我有一个长格式的表格,其中包含不同语言的物种名称和 2 级 id 编号,一个对应于该物种,另一个对应于该物种的不同名称。
例如:
species_list <- cbind.data.frame(num_sp= c(100,101,101,101,101,102,102,103), num_name = c(1,1,2,3,4,1,2,1), language=c("latin","latin", "english", "english", "english","latin","english","english"), name=c("marinus thingus", "aquaticus stuffae", "blob","water being","marine creature","altermarinus stuffae","other marine stuff", "unknown thingy"))
num_sp num_name language name
1 100 1 latin marinus thingus
2 101 1 latin aquaticus stuffae
3 101 2 english blob
4 101 3 english water being
5 101 4 english marine creature
6 102 1 latin altermarinus stuffae
7 102 2 english other marine stuff
8 103 1 english unknown thingy
我想要一个对应表,以便能够从英文名称中获取拉丁名称。我认为该表应该给我列中的语言,并且只有行中的 num_sp id,这对应于 i 的事情 a pivot_wider
,除了我的“num_sp”不是唯一标识符,所以该函数给出警告:
Warning message:
Values are not uniquely identified; output will contain list-cols.
有没有办法(通过 values_fn,也许?)将这些列表列拆分为不同的行,得到一个像这样的表:
num_sp english latin
1 100 <NA> marinus thingus
2 101 blob aquaticus stuffae
3 101 water being aquaticus stuffae
4 101 marine creature aquaticus stuffae
5 102 other marine stuff altermarinus stuffae
6 103 unknown thingy <NA>
谢谢你的时间!
解决方案
这将解决问题
species_list %>% pivot_wider(id_cols = num_sp,
names_from = language,
values_from = name,
values_fn = list) %>%
unnest(-num_sp)
# A tibble: 6 x 3
num_sp latin english
<dbl> <chr> <chr>
1 100 marinus thingus NA
2 101 aquaticus stuffae blob
3 101 aquaticus stuffae water being
4 101 aquaticus stuffae marine creature
5 102 altermarinus stuffae other marine stuff
6 103 NA unknown thingy
推荐阅读
- list - 批处理将列出文件夹中的文件,问我是哪一个,当我选择它时会打开它
- python - Python:在 1 秒内运行 N 次函数
- django - Django 测试客户端在尝试从谷歌云存储获取公共文件时给出 404。使用请求库时工作正常
- android - 我应该将哪个 Xamarin.Android apk 文件提供给 beta 测试人员
- android - Kotlin Coroutine 不执行多个挂起函数
- python - R:使用made函数删除时间序列季节性
- python - 如何根据索引删除部分列表
- python - 模板中的 Django ForeinKey
- ssh - 使用 WinSCP 命令将文件上传到 SFTP 时出现“主机密钥与配置的密钥不匹配”
- python - 如何在屏幕上显示键盘?