【问题标题】:Separating numeric values from charaters from R studio, tidyverse [duplicate]从Rstudio,tidyverse中分离数值和字符[重复]
【发布时间】:2020-03-31 06:32:06
【问题描述】:

所以我有一个看起来像这样的表:

ID <- c(1:10)
Response <- c("AUDIO", 6, 7, "Yes", 100, "AUDIO", 100, "NO", 9, 100)

tibble <- data.frame(ID, Response)

我想过滤掉诸如“音频”和“是”之类的字符答案,只留下数值,但不确定如何让 R 识别单独的类型。这是我到目前为止所尝试的。

new_tib <- tibble %>%
  mutate(Response = as.numeric(Response)) %>% 
  mutate(n = is.numeric(Response)) %>% 
  filter(n == TRUE) %>% 
  select(-n)

as.numeric() 似乎将字符元素强制转换为数字级别,而不是将它们转换为NA。有没有办法让 as.numeric 将字符强制转换为 NA 或更好的方法来分离这两种类型?

提前谢谢你!

【问题讨论】:

  • subset(tibble, grepl('\\d', Response))
  • 你可能想要as.numeric(as.character(...))

标签: r dplyr type-conversion


【解决方案1】:
# Base R solution:

df_only_numeric_responses <- df[grepl('\\d+', df$Response),]


# Tidyverse solution: 

require(tidyverse)

df %>% 
  filter(grepl('\\d+', Response))

# Data: 

df <- data.frame(ID = c(1:10),
                 Response = c("AUDIO", 6, 7, "Yes", 100, "AUDIO", 100, "NO", 9, 100),
                 stringsAsFactors = FALSE)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多