R 将列表的两个数据帧中的因子转换为数值
我无法将列表中2个数据帧的列转换为数字。现在,两个数据帧都有两列,由因子组成。我想把它们转换成数字,这样我就可以对它们进行数学运算。下面是示例代码:R 将列表的两个数据帧中的因子转换为数值,r,list,dataframe,factors,R,List,Dataframe,Factors,我无法将列表中2个数据帧的列转换为数字。现在,两个数据帧都有两列,由因子组成。我想把它们转换成数字,这样我就可以对它们进行数学运算。下面是示例代码: library(XML) bal <- "http://www.baseball-reference.com/teams/BAL/2014-schedule-scores.shtml" bos <- "http://www.baseball-reference.com/teams/BOS/2014-schedule-scores.sh
library(XML)
bal <- "http://www.baseball-reference.com/teams/BAL/2014-schedule-scores.shtml"
bos <- "http://www.baseball-reference.com/teams/BOS/2014-schedule-scores.shtml"
mylist <- list(bal, bos)
a <- lapply(mylist, readHTMLTable)
b <- lapply(a, function(x) x[["team_schedule"]][, c("R", "RA")])
c <- as.numeric(as.character(b))
以下是b的结构:
> str(b)
List of 2
$ :'data.frame': 165 obs. of 2 variables:
..$ R : Factor w/ 13 levels "","0","10","11",..: 6 6 7 8 10 7 6 5 9 2 ...
..$ RA: Factor w/ 13 levels "","0","1","10",..: 3 9 7 4 10 3 7 8 7 6 ...
$ :'data.frame': 166 obs. of 2 variables:
..$ R : Factor w/ 10 levels "","0","1","2",..: 3 8 6 4 8 2 7 9 6 3 ...
..$ RA: Factor w/ 13 levels "","1","10","14",..: 5 5 6 9 10 7 2 3 5 7 ...
要将因子转换为数值,我应该做什么不同的操作?您需要使用lappy。在“b”上执行a
str
这将让您知道您有一个2/2 data.frames的列表
因此,您需要使用Lappy和sapply来保留数据结构
lapply(b, function(x) sapply(x, function(x) as.numeric(as.character(x))))
您的系数中有D/N,它将转换为NAs和列表条目
空白/空白的在本例中不适用@RichardScriven
str(b)
lapply(b, function(x) sapply(x, function(x) as.numeric(as.character(x))))