在 R 中重铸特定的数据框列

兰吉·拉吉

我有一个三列的数据框titletextgrp

数据框如下所示:

标题 文本 grp
第 2 周 在第 2 周,编码... 2
注释 收集关于第 2 周的评论 2
统计数据 统计学是一门学科... 3
注释 收集关于统计的评论 3

我想将commentsas 列添加到此数据框中,并将值保留为与每个标题对应的文本。

所需的数据框:

标题 文本 注释 grp
第 2 周 在第 2 周,编码... 收集关于第 2 周的评论 2
统计数据 统计学是一门学科... 收集关于统计的评论 3

我尝试重新铸造:

library(reshape2)

recast(df, text ~ comment, id.var = c("text"))

但是给了我一个错误:

Error in unique.default(x) : unique() applies only to vectors
多哈迈德·德索基

尝试这个

library(dplyr , warn.conflicts = FALSE)

cdf <- df %>% filter(title == "comments") %>%  select( text, grp) 

colnames(cdf)[1] <- "comments"

nocdf <- df %>% select(title , text , grp) %>% filter(title != "comments")

new_df <- right_join(nocdf , cdf , by = "grp")

new_df %>% relocate(grp , .after = last_col())
#>        title                            text
#> 1     Week.2       In.Week.2.the.encoding...
#> 2 Statistics Statistics.is.the.discipline...
#>                                  comments grp
#> 1     collection.of.comments.about.Week.2   2
#> 2 collection.of.comments.about.Statistics   3

reprex 包(v2.0.1)创建于 2022-06-05

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章