R添加具有预定义模式的新列 [英] R add new column with predefined pattern

查看:57
本文介绍了R添加具有预定义模式的新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习如何提供可复制的R示例如果将来需要的话.

I'm trying to learn how to provide a reproducible R example in case I needed one in the future.

我使用SimSurv()函数,我想向其中添加六个新列(二进制变量).这些列的值不应平行或相交,即. var1对于元素1到100,其值必须为1,其余元素为0; var2将从101到200开始,依此类推.

I use the SimSurv() function and I want to add six new columns (binary variables) to it. These columns' values should not be parallel or intersecting ie. var1 must have the value 1 for elements 1 to 100 and the rest 0; var2 will start at 101 to 200 and so on.

x = SimSurv(600)
var1 = matrix(0:1, nrow=100) # 1 - 100
var2 = matrix(0:1, nrow=100) # 101 - 200
...
var6 = matrix(0:1, nrow=100) # 501 - 600

我无法在合法的Google搜索中表达这一观点,因此我在这里要求阐述我的问题.

I can not phrase this one into a legitimate Google search thus I asked here to expound my problem.

推荐答案

您可以使用gl()model.matrix():

y <- gl(6, 100)
mat <- model.matrix(~y-1) # -1 is for remove the intercept
colnames(mat) <- paste0('var', 1:6)
mat

这篇关于R添加具有预定义模式的新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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