r-如何根据另一列的数值序列动态添加列 [英] r - how to add columns dynamically based on numerical values sequences from another column

查看:237
本文介绍了r-如何根据另一列的数值序列动态添加列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何基于来自另一列的数值序列在数据框中动态添加列?我想根据来自另一列的值将 n 列添加到数据框中。我有什么,我想拥有什么:

How to add columns dynamically in a dataframe based on numerical values ​​sequences from another column? I want to add n columns into a dataframe based on values from another column. What do I have and what do I want to have:

我有这个:

head(df)
     x  y
[1]  1 ola
[2]  2 ola
[3]  3 ola
[4]  5 ola
[5]  4 ola
[6]  2 ola
[7]  3 ola
[8]  1 ola
[9]  5 ola
[10] 4 ola
[11] 2 ola
[12] 3 ola
[13] 5 ola
[14] 4 ola
[15] 1 ola
[16] 2 ola
[17] 3 ola
[18] 5 ola
[19] 4 ola
[20] 1 ola
[21] 3 ola
[22] 5 ola
[23] 2 ola
[24] 1 ola
[25] 4 ola
[26] 2 ola

在我的情况下,我有一个包含 18 列的数据框并且每列都有 3305708 行。那么,我想做什么?我想根据列值 x 动态添加列。也就是说,在这种情况下,添加更多 5 列,其值分别为 0 1 。像这样:

In my case, I have a dataframe with 18 columns and each columns has 3305708 rows. So, what do I want to do? I want to dynamically add columns based on column values ​​x. That is, in this case, add more 5 columns with values 0 and 1. Like this:

head(df)
     x   y   x_1 x_2 x_3  ...
[1]  1  ola   1   0   0   ...
[2]  2  ola   0   1   0   ...
[3]  3  ola   0   0   1   ...
[4]  5  ola   0   0   0   ...
[5]  4  ola   0   0   0   ...
[6]  2  ola   0   1   0   ...
[7]  5  ola   0   0   0   ...
[8]  1  ola   1   0   0   ...
[9]  5  ola   0   0   0   ...
[10] 4  ola   0   0   0   ...
[11] 2  ola   0   1   0   ...
[12] 3  ola   0   0   1   ...
[13] 5  ola   0   0   0   ...
[14] 4  ola   0   0   0   ...
[15] 1  ola   1   0   0   ...
[16] 2  ola   0   1   0   ...
[17] 3  ola   0   0   1   ...
[18] 5  ola   0   0   0   ...
[19] 4  ola   0   0   0   ...
[20] 1  ola   1   0   0   ...
[21] 3  ola   0   0   1   ...
[22] 5  ola   0   0   0   ...
[23] 2  ola   0   1   0   ...
[24] 1  ola   1   0   0   ...
[25] 4  ola   0   0   0   ...
[26] 2  ola   0   1   0   ...

如何动态执行此操作?在这种情况下,我只有 5 个值,但在我的情况下,我的列却具有 45 个值,以与我在此处相同的方式添加列。我该怎么做?

How can I do this dynamically? In this case I have just 5 values, but in my case I have columns that has 45 values and I have to add columns the same way I did here. How can I do this?

推荐答案

我们可以在上使用带有行顺序的'x'列和带有原始数据集的 cbind

We can use table on the 'x' column with the sequence of rows and cbind with the original dataset

res <- cbind(df, as.data.frame.matrix(table(seq_len(nrow(df)), df$x)))
names(res) <-  tolower(make.names(names(res)))
res
#   x   y x1 x2 x3 x4 x5
#1 1 ola  1  0  0  0  0
#2 2 ola  0  1  0  0  0
#3 3 ola  0  0  1  0  0
#4 5 ola  0  0  0  0  1
#5 4 ola  0  0  0  1  0
#6 2 ola  0  1  0  0  0

这篇关于r-如何根据另一列的数值序列动态添加列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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