r - 仅将 tidyr 单独应用于特定行

标签 r dataframe tidyr

我正在尝试使用 tidyr 来分隔数据框中的一列,同时仅将其应用于特定行。虽然 dplyr::filter 完成了这项工作,但它忽略了我的其余数据。是否有一种干净的方法将 tidyr 应用于特定行,同时保持其余数据不变?

这是我的问题的一个示例:

#creating DF for the example
df<-data.frame(var_a=letters[1:5],
               var_b=c(sample(1:100,5)),
               text=c("foo_bla","here_do","oh_yes","baa","land"))

给了我这个:

  var_a var_b    text
1     a    10 foo_bla
2     b    58 here_do
3     c    34  oh_yes
4     d     1     baa
5     e    47    land
#separating one col:
clean_df<-df %>% separate(text,into=c("first","sec"),sep="_",remove=F)
clean_df
  var_a var_b    text first  sec
1     a    10 foo_bla   foo  bla
2     b    58 here_do  here   do
3     c    34  oh_yes    oh  yes
4     d     1     baa   baa <NA>
5     e    47    land  land <NA>

I want to split only the "here_do" row. Thanks in advance for any kind of help!

最佳答案

另一种方法:

cols_to_split = c('here_do')

clean_df <-df %>% 
     filter(text %in% cols_to_split) %>% 
     tidyr::separate(text,into=c("first","sec"),sep="_",remove=F) %>% 
     bind_rows(filter(df, !text %in% cols_to_split))


#  var_a var_b    text first  sec
#1     b     7 here_do  here   do
#2     a    26 foo_bla  <NA> <NA>
#3     c    23  oh_yes  <NA> <NA>
#4     d     2     baa  <NA> <NA>
#5     e    67    land  <NA> <NA>

如果您需要将其余行保留在“first”列中,您可以使用:

clean_df <-df %>% 
     filter(text %in% cols_to_split) %>% 
     tidyr::separate(text,into=c("first","sec"),sep="_",remove=F) %>% 
     bind_rows(filter(df, !text %in% cols_to_split)) %>% 
     mutate(first = ifelse(is.na(first), as.character(text), first))

#  var_a var_b    text   first  sec
#1     b     7 here_do    here   do
#2     a    26 foo_bla foo_bla <NA>
#3     c    23  oh_yes  oh_yes <NA>
#4     d     2     baa     baa <NA>
#5     e    67    land    land <NA>

关于r - 仅将 tidyr 单独应用于特定行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41506310/

相关文章:

r - 在执行中停止 dplyr/tidyr 链并保存计算进度

r - 使用ggplot2创建一个facet_wrap图,每个图中都有不同的注释

r - 在 R 包中使用 tidy eval

r - 新手使用 csv 文件在 R 中的 map 上绘制坐标

python-2.7 - df.fillna(0) 命令不会用 0 替换 NaN 值

r - 宽到长数据转换多列

r - Latex 的概率边际效应输出

rbind.data.frame的性能

python - 如何使用 Pandas 中另一列的长度作为切片参数

r - 优化runtime : change the weight of edges in an igraph takes long time. 请问有什么办法可以优化吗?