将列表的两个数据帧中的因子转换为数字 [英] Convert Factors in 2 Data Frames of a List into Numeric

查看:132
本文介绍了将列表的两个数据帧中的因子转换为数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法将列表中的2个数据帧的列转换为数字。现在,两个数据帧都有2列由因素组成。我想将它们转换成数字,以便我们可以对它们进行数学运算。以下是示例代码:

I am having trouble converting the columns of 2 data frames in a list to numeric. Right now both data frames have 2 columns consisting of factors. I want to convert them to numeric so that I can do mathematical operations on them. Below is sample code:

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))

当我运行这段代码时,我得到:

When I run this code I get:

> c
[1] NA NA
> str(c)
 num [1:2] NA NA

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 ...

我应该怎么做不同的将因素转换为数值?

What should I do differently to convert the factors into numeric values?

推荐答案

你需要使用lapply。在b上执行 str

You need to use lapply. do a str on "b"

str(b)

这将让您知道您有2个data.frames的2个列表。

This will let you know you have a list of 2 of 2 data.frames.

所以你需要使用lapply来保存数据结构

So you need to use lapply along with sapply, to preserve the data structure

lapply(b, function(x) sapply(x, function(x) as.numeric(as.character(x))))

您的系数中有D / N,将转换为NAs,还可以将空白/空的列表条目

You have D/N in your factor, which will be converted to NAs and also the list entries that are blank/empty

这篇关于将列表的两个数据帧中的因子转换为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆