【问题标题】:R remove numbers in data frame entries containing only numbersR删除仅包含数字的数据框条目中的数字
【发布时间】:2018-05-16 02:03:24
【问题描述】:

我正在从在线 csv 文件中读取数据框,但创建文件的人不小心在列中输入了一些数字,这些数字应该只是城市名称。 cities.data 表的示例。

City        Population   Foo   Bar
Seattle     10           foo1  bar1
98125       20           foo2  bar2
Kent 98042  30           foo3  bar3
98042 Kent  30           foo4  bar4

删除城市列中只有数字的行后所需的输出:

City        Population   Foo   Bar
Seattle     10           foo1  bar1
Kent 98042  30           foo3  bar2
98042 Kent  30           foo4  bar4

我想删除城市列中只有数字的行。 Kent 98042 和 98042 Kent 都可以,因为它包含城市名称,但由于 98125 不是城市,我删除了该行。

我无法使用is.numeric,因为该数字在 csv 文件中被读取为字符串。我尝试使用正则表达式,

cities.data <- cities.data[which(grepl("[0-9]+", cities.data) == FALSE)]

但这会删除包含任何数字的行,而不仅仅是只包含数字的行,例如

City        Population   Foo   Bar
Seattle     10           foo1  bar1

"Kent 98042" 已被删除,即使我想保留该行。 建议?请和谢谢!

【问题讨论】:

  • 你想在文本之后保留这些数字吗?例如,在您想要的输出中,第三个观察值必须是“Kent 98042”还是“Kent”正常?
  • 尝试添加字符串grepl("^[0-9]+", cities.data)的强制开头
  • 我不需要城市后面的数字,只需要“肯特”就可以了,但我认为这样做可能会更难。哦,对不起,我忘了包括一个数字在城市前面的例子,例如“98042 Kent”导致“^”不起作用,因为它消除了该行。
  • @siushi 我刚刚在下面添加了一个解决方案,可以在删除所有数字的同时解决它,并且还应该处理文本前的情况。

标签: r regex dataframe filter dplyr


【解决方案1】:

如果您根本不需要城市列中的数字:

# replace all numbers with empty string
cities.data$City <- gsub("[0-9]+", "", cities.data$City) 
# drop observations that are only empty strings
cities.data <- cities.data[cities.data$City!="",]  

edit:这应该处理更新示例中的所有情况,其中数字可以位于字符串中的任何位置。

【讨论】:

  • 谢谢!这很棒,因为它比我想要的要早一步。
  • 太棒了!很高兴我能帮上忙!如果它是您使用的那个,我会很感激您接受我的回答。
【解决方案2】:
df = read.table(text = "
City        Population   Foo   Bar
Seattle     10           foo1  bar1
98125       20           foo2  bar2
Kent98042  30           foo3  bar2
", header=T, stringsAsFactors=F)

library(dplyr)

df %>% filter(is.na(as.numeric(City)))

#        City Population  Foo  Bar
# 1   Seattle         10 foo1 bar1
# 2 Kent98042         30 foo3 bar2

这个想法是,当我们将as.numeric 应用于字符变量时,它不会返回NA 值,只有当它是一个数字时。

如果你想使用base R,你可以使用这个:df[is.na(as.numeric(df$City)),]

【讨论】:

    【解决方案3】:

    用纯R

    df <- data.frame(City = c('Seattle', '98125', 'Kent 98042'),
                     Population = c(10, 20, 30),
                     Foo = c('foo1', 'foo2', 'foo3'))
    df2 <- df[-grep('^\\d+$', df$City),]
    df2
    

    这会产生

            City Population  Foo
    1    Seattle         10 foo1
    3 Kent 98042         30 foo3
    


    这个想法是寻找^\d+$(只有数字)并从集合中删除这些。注意两边的锚。

    【讨论】:

    • 谢谢!我不太擅长正则表达式,也不知道我可以锚定表达式的末端。
    猜你喜欢
    • 2021-10-13
    • 2015-07-04
    • 1970-01-01
    • 1970-01-01
    • 2020-04-14
    • 2019-12-02
    • 2021-08-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多