相关疑难解决方法(0)

R中模型矩阵中因子的所有级别

我有一个data.frame数字和因子变量组成,如下所示.

testFrame <- data.frame(First=sample(1:10, 20, replace=T),
           Second=sample(1:20, 20, replace=T), Third=sample(1:10, 20, replace=T),
           Fourth=rep(c("Alice","Bob","Charlie","David"), 5),
           Fifth=rep(c("Edward","Frank","Georgia","Hank","Isaac"),4))
Run Code Online (Sandbox Code Playgroud)

我想构建一个matrix为该因子分配虚拟变量并单独保留数值变量.

model.matrix(~ First + Second + Third + Fourth + Fifth, data=testFrame)
Run Code Online (Sandbox Code Playgroud)

正如预期的那样,在运行时会将lm每个因子的一个级别作为参考级别.但是,我想为matrix所有因素的每个级别构建一个带有虚拟/指示变量的变量.我正在建立这个矩阵,glmnet所以我不担心多重共线性.

有没有办法model.matrix为每个级别的因子创建假人?

model r matrix indicator

62
推荐指数
4
解决办法
5万
查看次数

R"爆炸"数据帧的列

我有一个非常有趣的问题,我正在寻找一个聪明且可能有效的解决方案.

我有一个看起来像这样的数据框.

# A tibble: 6 x 6
  track_id   tag1   tag2  tag3   tag4   tag5
     <int>  <dbl>  <dbl> <dbl>  <dbl>  <dbl>
1  1550729  54087 109806 46869 183258  54337
2  1184201 201327   3668 46208 205245 189631
3  3763749 194264 194413  3424  91383 205245
4  2674608 198998 107401  2327   4425 107398
5  1999180  54087   4425 75574 239459   2397
6  3048820  11242 205245  2474  11056  72354
Run Code Online (Sandbox Code Playgroud)

我想要的是将track_id保留在第一行但是要爆炸标签,并且在一个轨道具有特定ID的情况下,我想要设置一个真值,即一个.

为了更清楚,让我们假设我从较小的一个开始:

  track_id   tag1   tag2 
1  1550729  54087 109806 
2  1184201 201327   3668 
Run Code Online (Sandbox Code Playgroud)

转型后,我想得到类似的东西

  track_id   54087   109806  201327 …
Run Code Online (Sandbox Code Playgroud)

r dataframe dplyr

0
推荐指数
1
解决办法
755
查看次数

标签 统计

r ×2

dataframe ×1

dplyr ×1

indicator ×1

matrix ×1

model ×1