R:使用 select_if() 和 gsub() 时将字符类型转换为数字类型时出错
R: Error converting character type to numeric type when using select_if() and gsub()
我有一个多种类型的数据集。它是在 Excel 电子表格中创建的,因此一些数字包含逗号(例如 1,346 而不是 1346)。因此,使它们成为字符类型而不是数字类型。
这是我试图进行转换的内容:
df[-2] %>%
select_if(is.character) %>%
as.numeric(gsub(",", "", df))
我将第二列排除在选择之外,因为它是我分析的有效字符类型。
我得到的错误是:
Error in df[-2] %>% select_if(is.character) %>% as.numeric(gsub(",", :
'list' object cannot be coerced to type 'double'
我怎样才能完成这项工作?
如果我们需要这样做以将所有 character
列上的 ,
替换为空白 (""
),请使用 mutate
和 across
因为 gsub/sub
等在 vector
作为输入而不是在 data.frame
上工作
library(stringr)
library(dplyr)
df1 <- df %>%
mutate(across(where(is.character), ~ as.numeric(str_remove_all(., ','))))
如果我们要排除第二列
df1 <- df %>%
mutate(across(c(where(is.character), -2), ~
as.numeric(str_remove_all(., ','))))
请注意,select_if
或 select(where
只会 select 原始数据中的那些列。如果打算替换原始数据集列中的 ,
,请使用 mutate
和 across
数据
df <- structure(list(col1 = 1:5, col2 = c("a", "b", "c", "d", "e"),
col3 = c("1,2", "1,5", "1,3", "1,44", "1,46"), col4 = c("1,2",
"1,5", "1,3", "1,44", "1,46")), class = "data.frame", row.names = c(NA,
-5L))
我有一个多种类型的数据集。它是在 Excel 电子表格中创建的,因此一些数字包含逗号(例如 1,346 而不是 1346)。因此,使它们成为字符类型而不是数字类型。
这是我试图进行转换的内容:
df[-2] %>%
select_if(is.character) %>%
as.numeric(gsub(",", "", df))
我将第二列排除在选择之外,因为它是我分析的有效字符类型。
我得到的错误是:
Error in df[-2] %>% select_if(is.character) %>% as.numeric(gsub(",", :
'list' object cannot be coerced to type 'double'
我怎样才能完成这项工作?
如果我们需要这样做以将所有 character
列上的 ,
替换为空白 (""
),请使用 mutate
和 across
因为 gsub/sub
等在 vector
作为输入而不是在 data.frame
library(stringr)
library(dplyr)
df1 <- df %>%
mutate(across(where(is.character), ~ as.numeric(str_remove_all(., ','))))
如果我们要排除第二列
df1 <- df %>%
mutate(across(c(where(is.character), -2), ~
as.numeric(str_remove_all(., ','))))
请注意,select_if
或 select(where
只会 select 原始数据中的那些列。如果打算替换原始数据集列中的 ,
,请使用 mutate
和 across
数据
df <- structure(list(col1 = 1:5, col2 = c("a", "b", "c", "d", "e"),
col3 = c("1,2", "1,5", "1,3", "1,44", "1,46"), col4 = c("1,2",
"1,5", "1,3", "1,44", "1,46")), class = "data.frame", row.names = c(NA,
-5L))