【问题标题】:Splitting a dataframe if rows are numeric or not in R如果行是数字或不是R中的数字,则拆分数据框
【发布时间】:2015-10-27 18:21:11
【问题描述】:

我有一个数据框(我们称之为“df”),它由两列组成

 Name   Contact
 A      34552325
 B      423424
 C      4324234242
 D      hello1@company.com

我想根据“联系人”列中的一行是否为数字将数据框拆分为两个数据框

预期输出:

 Name   Contact
 A      34552325
 B      423424
 C      4324234242

 Name   Contact
 D      hello1@company.com

我厌倦了使用:

   df$IsNum <- !(is.na(as.numeric(df$Contact))) 

但这也将“hello1@company.com”归类为数字。

基本上,如果“联系人”列中甚至有一个非数字值,那么代码必须将其归类为非数字

【问题讨论】:

  • 你可能有因素,所以as.numeric 行不通,试试split(df, is.na(as.numeric(as.character(df$Contact)))) 可能
  • 在我完成df$Contact &lt;- as.vector(df$Contact) 之后,我采用了您的方法。我也喜欢这个df$IsNum &lt;- suppressWarnings({!(is.na(as.numeric(df$Contact)))}),以摆脱warning message

标签: r dataframe table-splitting


【解决方案1】:

您可以使用grepl..

x <- " Name   Contact
 A      34552325
 B      423424
 C      4324234242
 D      hello1@company.com"
df <- read.table(text=x, header = T)
x <- df[grepl("^\\d+$",df$Contact),]
y <- df[!grepl("^\\d+$",df$Contact),]
x
#   Name    Contact
# 1    A   34552325
# 2    B     423424
# 3    C 4324234242
y
#  Name            Contact
# 4    D hello1@company.com

【讨论】:

    【解决方案2】:

    我们可以使用grepl(与@Avinash Raj 创建的方式相同)创建一个分组变量,split 使用该数据框创建一个list 的data.frames。

    split(df, grepl('^\\d+$', df$Contact))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-17
      • 2018-07-08
      • 1970-01-01
      • 2021-05-23
      • 1970-01-01
      • 2012-11-02
      相关资源
      最近更新 更多