【问题标题】:integer type split into two columns整数类型分成两列
【发布时间】:2017-11-27 21:52:28
【问题描述】:

我的列中有两个由“->”分隔的字母数字字符,我正在尝试将它们拆分为列。


Df:

 column e 
1. asd1->ref2
2. fde4 ->fre4
3. dfgt-fgr ->frt5
4. ftr5 -> lkh-oiut
5. rey6->usre-lynng->usre-lkiujh->kiuj-bunny
6. dge1->fgt4->okiuj-dfet

期望的输出

  col 1    col 2
1. asd1     ref2
2. fde4     fre4
3.          frt5
4. ftr5 
5. rey6
6. dge1     fgt4

我尝试使用没有输出的out <- strsplit(as.character(Df$column e),'_->_') 并使用str_extract(m1$column e,"(?<=\\[)[[:alnum:]]")->m1$column f,也使用了 strsplit(as.character(Df$column e),' -> 'fixed=T)[[1]][[1]] 但是没有得到想要的输出。

if 列是整数类型,都是大写字母(不知道是不是小数)

【问题讨论】:

  • 我认为应该注意Df$column e 可能会混淆事情。您可能需要删除该列名中的空格 (Df$columne),或引用列名 (Df$'column e')。
  • 对,我的专栏的实际名称是 Df$column.e
  • @ycw,请注意。在最后一个问题中,我得到了正确的输出,但它正在复制数据框中存在的其他列并将其粘贴到原始列旁边。
  • @ycw,问题是一样的,但找到了两个新的解决方案来解决我的问题。我会确保不再重复问题。感谢您的帮助

标签: r split


【解决方案1】:

这是tidyverse的一种方法

library(tidyverse)
df1 %>% 
    separate(columne, into = c('col1', 'col2'), sep = "->", extra = 'drop') %>% 
    mutate_all(funs(replace(., str_detect(., '-'), "")))
#   col1 col2
#1  asd1 ref2
#2 fde4  fre4
#3       frt5
#4 ftr5      
#5  rey6     
#6  dge1 fgt4

【讨论】:

  • 这行得通,谢谢。我试图使用 df1 %>% separate(columne, into = c('col1', 'col2'), sep = "->", extra = 'drop') %>% mutate_all(funs(replace(., str_detect(., '-'), ""))) ->Df$lk 将列添加到我的原始数据框中,它正在复制数据框并在最后添加它,我怎样才能将两列 col1 和 col2 添加到我的原始数据框中而不重复任何其他列
  • @kishore 如果我们需要恢复原始列,可以使用separate 参数remove = FALSE。即df1 %>% separate(columne, into = c('col1', 'col2'), sep = "->", extra = 'drop', remove = FALSE) %>% mutate_at(vars(matches("col\\d+")), funs(replace(.,
【解决方案2】:

还有一个base R 解决方案,虽然比@akrun 的tidyverse 简单一点:

# split as appropriate
out <- strsplit( as.character( Df$column.e ), '->' )

out <- lapply( out, function(x) {

    # I assume you don't want the white space
    y <- trimws( x )

    # take the first two "columns"
    y <- y[1:2]

    # remove any items containing a hyphen
    y[ grepl( "-", y ) ] <- ""
    y
    }
)

# then bind it all rowwise
out <- do.call( rbind, out )
data.frame( out )

    X1   X2
1 asd1 ref2
2 fde4 fre4
3      frt5
4 ftr5     
5 rey6     
6 dge1 fgt4

【讨论】:

  • 是的,这很好用。谢谢 :)。我们可以命名这个函数中的列吗?
  • 是的,有几种方法可以做到这一点。可能最简单的方法是在最后分配它们names(df)&lt;-c("col1","col2")
猜你喜欢
  • 2014-04-18
  • 1970-01-01
  • 2016-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多