无法在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
答案 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