我正在尝试执行主成分分析,但我收到错误:colMeans中的错误(x,na.rm = TRUE):'x'必须是数字
我知道所有列都必须是数字,但是当数据集中有字符对象时如何处理? E.g:
data(birth.death.rates.1966)
data2 <- birth.death.rates.1966
princ <- prcomp(data2)
我是否应该将引用国家/地区名称的新列添加到数字代码中?如果是,如何在R?
中执行此操作答案 0 :(得分:6)
您可以通过factor
将字符向量转换为数字值。然后每个唯一值获得唯一的整数代码。在这个例子中,有四个值,所以数字是1到4,按字母顺序,我认为:
> d = data.frame(country=c("foo","bar","baz","qux"),x=runif(4),y=runif(4))
> d
country x y
1 foo 0.84435112 0.7022875
2 bar 0.01343424 0.5019794
3 baz 0.09815888 0.5832612
4 qux 0.18397525 0.8049514
> d$country = as.numeric(as.factor(d$country))
> d
country x y
1 3 0.84435112 0.7022875
2 1 0.01343424 0.5019794
3 2 0.09815888 0.5832612
4 4 0.18397525 0.8049514
然后您可以运行prcomp
:
> prcomp(d)
Standard deviations:
[1] 1.308665216 0.339983614 0.009141194
Rotation:
PC1 PC2 PC3
country -0.9858920 0.132948161 -0.101694168
x -0.1331795 -0.991081523 -0.004541179
y -0.1013910 0.009066471 0.994805345
这对您的应用程序是否有意义取决于您。也许您只想删除第一列:prcomp(d[,-1])
并使用数字数据,这似乎是其他“答案”试图实现的目标。
答案 1 :(得分:1)
数据框的第一列是字符。因此,您可以将其重新编码为行名称:
<?php
try{
$pdo = new PDO("mysql:host=localhost;dbname=menu",'root','');
} catch (PDOException $ex) {
echo $ex->getMessag();
}
$sql = "SELECT * FROM menu ORDER BY id";
$stmt = $pdo->prepare($sql);
$stmt->execute();
?>
<!DOCTYPE html>
<html>
<head>
<meta name="author" content="Kayla Lindstrom">
<title>Lindstrom Letters</title>
<!-- <link rel="stylesheet" type="text/css" href="style.css">-->
</head>
<body>
<div id="page">
<ul>
<?php while ($row = $stmt->fetch(PDO::FETCH_OBJ)) {
$sub_sql = "SELECT * FROM people WHERE menu_id=:id";
$sub_stmt = $pdo->prepare($sub_sql);
$sub_stmt->bindParam(':id', $row->id,PDO::PARAM_INT);
$sub_stmt->execute();
?>
<li><a href=""><?php echo $row->name; ?></a>
<?php if($sub_stmt->rowCount()){ ?>
<ul>
<?php while($sub_row = $sub_stmt->fetch(PDO::FETCH_OBJ)) {
$sub2_sql = "SELECT * FROM letters WHERE people_id=:id"; /*Here is where I am stuck.*/
$sub2_stmt = $pdo->prepare($sub2_sql);
$sub2_stmt->bindParam(':id', $row->id,PDO::PARAM_INT);/*and here*/
$sub2_stmt->execute(); ?>
<li><a href="<?php echo $sub_row->href; ?>">
<?php echo $sub_row->people_name;?></a>
<?php if($sub2_stmt->rowCount()){ ?>
<ul>
<?php while($sub2_row = $sub2_stmt->fetch(PDO::FETCH_OBJ)) { ?>
<li><a href="<?php echo $sub2_row->href; ?>">
<?php echo $sub2_row->letters_name;?></a></li>
<?php } ?>
</ul>
<?php } ?>
</li>
<?php } ?>
</ul>
<?php } ?>
</li>
<?php } ?>
</ul>
</div>
</body>
</html>
或者作为:
library(tidyverse)
data2 %>% remove_rownames %>% column_to_rownames(var="country")
princ <- prcomp(data2)
答案 2 :(得分:0)
在R中,将factor方法添加到数据字符集并不会使其成为数字。 实际上,这是使我们的机器学习模型成为数学模型,而不是数字数据。
示例:如果您有一个名称列表,然后对它们进行数字编码,则某个名称可能会具有较高的数值,这将根据我们的模型为它赋予不同的定义。
名称(文本数据仅用于标记特定集合)通常不应该定义模型的工作方式。
此外,如果您尝试使用假定为数字的此数据,则可能会出现以下错误:
colMeans(x,na.rm = TRUE)中的错误:“ x”必须为数字
我已经定义了为什么您可能会在上方看到此错误
要克服这个问题
training_set[,2:3] = scale(training_set)
test_set[,2:3] = scale(test_set)
在下图中,第1列和第4列已编码数据,不能视为数字模型。第2列和第3列最初包含数字数据,因此我们只能在该部分数据上运行模型。上面的代码仅显示了如何选择包含所有行以及第2和第3列的数据