r - 在涉及因素的情况下用向量创建矩阵

原文 标签 r matrix statistics

Creating a matrix with vectors, when there are factors involved

I almost reached the end of the internet, but I couldn't find the (exact) answer to my question!

It's probably very easy, but I just want to select some variables from a dataframe, to form a matrix with some of its vectors. So mainly what happend is printed in my example below:

treatment <- factor(rep(c(1, 2), c(43, 41)), levels = c(1, 2),
    labels = c("placebo", "treated"))

improved <- factor(rep(c(1, 2, 3, 1, 2, 3), c(29, 7, 7, 13, 7, 21)),
    levels = c(1, 2, 3),
    labels = c("none", "some", "marked"))

numberofdrugs<-rpois(84, 2)

X<-cbind(numberofdrugs, treatment, improved)

X #"why are the units numbers and not names

The problem that I've got is, that R is converting factors to numbers. For example "male" and "female" to "0" and "1". But I don't want that! What am I supposed to do?

Answer

This is documented behaviour of cbind. From ?cbind: "Any classes the inputs might have are discarded (in particular, factors are replaced by their internal codes.)"

You should use data.frame instead:

X <- data.frame(numberofdrugs, treatment, improved)
head(X)

  numberofdrugs treatment improved
1             0   placebo     none
2             1   placebo     none
3             0   placebo     none
4             5   placebo     none
5             1   placebo     none
6             4   placebo     none

翻译

我几乎到达了互联网的尽头,但是我找不到我的问题的(确切)答案!

这可能很容易,但是我只想从数据框中选择一些变量,以形成带有某些向量的矩阵。因此,主要是在下面的示例中打印了发生的情况:

treatment <- factor(rep(c(1, 2), c(43, 41)), levels = c(1, 2),
    labels = c("placebo", "treated"))

improved <- factor(rep(c(1, 2, 3, 1, 2, 3), c(29, 7, 7, 13, 7, 21)),
    levels = c(1, 2, 3),
    labels = c("none", "some", "marked"))

numberofdrugs<-rpois(84, 2)

X<-cbind(numberofdrugs, treatment, improved)

X #"why are the units numbers and not names


我遇到的问题是R正在将因子转换为数字。例如,“男性”和“女性”分别为“ 0”和“ 1”。但是我不要那个!我应该做些什么?
最佳答案
这是cbind的已记录行为。来自?cbind:“任何可能输入的类都将被丢弃(尤其是因数用其内部代码代替。”)

您应该使用data.frame代替:

X <- data.frame(numberofdrugs, treatment, improved)
head(X)

  numberofdrugs treatment improved
1             0   placebo     none
2             1   placebo     none
3             0   placebo     none
4             5   placebo     none
5             1   placebo     none
6             4   placebo     none
相关推荐

r - 借助有用的帮助改进R编码

list - 查找工作空间中所有数据框中所有列的名称

r - ddply如何将因子作为“拆分”变量处理?

r - 从源文件安装R软件包

r - 使用.onLoad加载依赖的软件包

r - 在点图(ggplot)中添加线交叉因子

r - R中的chisq.test

r - 用ggplot2绘制热图;对数刻度颜色和修改颜色图例

r - 如何使用R将“ TRUE FALSE”组合为“ FALSE”?

r - 如何确定哪个Sweave代码块给出错误?