Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/79.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 将行从因子转换为数值?_R - Fatal编程技术网

R 将行从因子转换为数值?

R 将行从因子转换为数值?,r,R,这个例子: dat=structure(list(X = structure(c(1L, 2L,3L), .Label = c("A", "B", "C"), class = "factor"), X10 = structure(c(1L,2L,3L), .Label = c("3","0", "2"), class = "factor"), X11 = structure(c(1L, 2L,3L), .Label = c("0", "2", "0"), class = "factor")),

这个例子:

dat=structure(list(X = structure(c(1L, 2L,3L), .Label = c("A", "B", "C"), class = "factor"), X10 = structure(c(1L,2L,3L), .Label = c("3","0", "2"), class = "factor"), X11 = structure(c(1L, 2L,3L), .Label = c("0", "2", "0"), class = "factor")), class = "data.frame", row.names = c(NA, -3L)) 

 dat=dat[,-1]

 fi=as.numeric(as.character(dat[1,] ))

 > fi
[1] 1 1

这是不正确的。我想知道怎么了?

由于.numeric
用于矢量,如果要将其应用于数据帧,则需要使用apply:

apply(dat, MARGIN=2,FUN=as.numeric)
结果:

      X10 X11
[1,]   3   0
[2,]   0   2
[3,]   2   0

由于.numeric
用于矢量,如果要将其应用于数据帧,则需要使用apply:

apply(dat, MARGIN=2,FUN=as.numeric)
结果:

      X10 X11
[1,]   3   0
[2,]   0   2
[3,]   2   0

对于不同类别的多个列,我们可以检查是否为
因子
,以进行转换

library(dplyr)
dat %>%
    mutate_if(is.factor, funs(as.numeric(as.character(.))))
如果所有列都是
factor
,则使用
mutate\u all

dat %>%
   mutate_all(funs(as.numeric(as.character(.))))

base R
方法如果所有列都是
factor
,则使用
lapply
并将其指定给原始对象

dat[] <- lapply(dat, function(x) as.numeric(as.character(x)))

dat[]对于不同类别的多个列,我们可以检查它是否是
因子
来进行转换

library(dplyr)
dat %>%
    mutate_if(is.factor, funs(as.numeric(as.character(.))))
如果所有列都是
factor
,则使用
mutate\u all

dat %>%
   mutate_all(funs(as.numeric(as.character(.))))

base R
方法如果所有列都是
factor
,则使用
lapply
并将其指定给原始对象

dat[] <- lapply(dat, function(x) as.numeric(as.character(x)))

dat[]如果您是为第一行执行此操作,则执行
as.numeric(as.character(unlist(dat[1,]))
如果您是为第一行执行此操作,则执行
as.numeric(as.character(unlist(dat[1,]))
它们是列标题,看起来不像这样,因为我是从R控制台复制的。它们是列标题,看起来不是这样,因为我是从R控制台复制的。