如何解决如何通过复制值来透视和填充缺少的值
我试图从长格式到宽格式获取数据帧,但是由于其结构,每当我使用ivot_wider()时,我都会得到两列包含数据向量的列。
这是原始数据:
( A lookbehind assertion has to be fixed width
* A quantifier inside a lookbehind makes it non-fixed width
) A lookbehind assertion has to be fixed width
* A quantifier inside a lookbehind makes it non-fixed width
我使用的命令:
structure(list(type = c("radio","radio","television","television"
),Resource = c("samsung","samsung","sony","sony"
),Property = c("lot_number","lot_number","manufacturer","other_PN","part_number","part_number"
),value = c("12345","54321","John","9876","12345","56789","67890","Walt","5g6h3f","6789","2a3b4c","3461")),class = c("spec_tbl_df","tbl_df","tbl","data.frame"),row.names = c(NA,-19L),spec = structure(list(
cols = list(type = structure(list(),class = c("collector_character","collector")),Resource = structure(list(),Property = structure(list(),value = structure(list(),"collector"))),default = structure(list(),class = c("collector_guess",skip = 1),class = "col_spec"))
但多个值将作为矢量保存在“ lot_number”列中:
df_wide <- df %>% pivot_wider(names_from = Property,values_from = value)
这是我想最后获得的数据帧。注意,在所需的输出中,“ radio”缺少一些值。另外,“制造商”,“ other_PN”和“ part_number”列中的值也必须在多行中重复。
structure(list(type = c("radio","television"),"sony"),lot_number = list(
c("12345","54321"),c("9876","67890"),"67890"
)),manufacturer = list("John","John"),other_PN = list(
NULL,"2a3b4c"),part_number = list(NULL,-3L),class = c("tbl_df","data.frame"))
感谢您的帮助!
解决方法
我建议使用您的dput()
数据作为df
的这种方法。您可以使用group_by()
创建一个id变量以标识行,然后可以使用pivot_wider()
进行整形。由于需要填充某些值,因此可以使用fill()
的{{1}}包中的tidyr
:
tidyverse
输出:
library(tidyverse)
#Data
df %>% group_by(type,Resource,Property) %>% mutate(id=1:n()) %>%
pivot_wider(names_from = Property,values_from=value) %>%
fill(everything()) %>% select(-id)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。