使用tidyverse将具有千位分隔符值的多个因子列转换为整数

时间:2017-01-18 20:55:04

标签: r tidyverse

无法在SO上找到确切的解决方案,无论如何都希望使用tidyverse R套件的最简洁版本。希望除了第一列之外的所有列都是整数,并且在现实生活中支持更多列

df <- structure(list(col_1 = structure(1:3, .Label = c("a", "b", "c"
), class = "factor"), col_2 = structure(c(1L, 3L, 2L), .Label = c("1,234", 
"23", "4,567"), class = "factor"), col_3 = structure(1:3, .Label = c("1234", 
"46", "6,789"), class = "factor")), .Names = c("col_1", "col_2", 
"col_3"), row.names = c(NA, -3L), class = "data.frame")

TIA

3 个答案:

答案 0 :(得分:1)

在列中查找",",如果存在,则将该列设为数字:

df1 = lapply(df, function(x) {if(any(grepl(",", x))){x<-as.numeric(gsub(",", "", x))};x})
# as.data.frame(df1)
#  col_1 col_2 col_3
#1     a  1234  1234
#2     b  4567    46
#3     c    23  6789

答案 1 :(得分:0)

您可以使用mutate_at,排除第一列,使用gsub删除逗号,然后将其转换为整数:

library(tidyverse)
df %>% mutate_at(.cols = -1, funs(as.integer(gsub(",", "", .))))

#  col_1 col_2 col_3
#1     a  1234  1234
#2     b  4567    46
#3     c    23  6789

使用parse_number的另一个选项,但这会给出数字列:

df %>% mutate_at(.cols = -1, funs(parse_number))

#  col_1 col_2 col_3
#1     a  1234  1234
#2     b  4567    46
#3     c    23  6789

答案 2 :(得分:0)

以下是data.table的版本。将'data.frame'转换为'data.table'(setDT(df)),在.SDcols中指定感兴趣的列,使用lapply循环显示它们,替换,gsub中使用空格,转换为integer并将其分配(:=)回到列

library(data.table)
setDT(df)[, (2:3) := lapply(.SD, function(x)
       as.integer(gsub(",", "", x))), .SDcols = 2:3]
df
#   col_1 col_2 col_3
#1:     a  1234  1234
#2:     b  4567    46
#3:     c    23  6789