简体   繁体   English

更改具有唯一值的多列中的值并合并为单列 (R)

[英]Change values in multiple columns with unique value and merge into single column (R)

Let's say I have a dataset (ds) with 4 rows with 3 variables as seen below:假设我有一个包含 3 个变量的 4 行数据集 (ds),如下所示:

ds
x1  x2  x3
 1   0   0
 0   0   1
 0   1   0
 0   0   1

How do I change the "1" to a unique value for each column and combine them into a single column?如何将每列的“1”更改为唯一值并将它们合并为一列?

So, the first step:所以,第一步:

x1  x2  x3
 1   0   0
 0   0   3
 0   2   0
 0   0   3

Then, the second step (creating x4 ):然后,第二步(创建x4 ):

x1  x2  x3  x4
 1   0   0   1
 0   0   3   3
 0   2   0   2
 0   0   3   3

I have a lot more variables than this, I just want to know how to minimize the number of lines I write so it's not like 10+ lines.我有比这更多的变量,我只是想知道如何最大限度地减少我写的行数,所以它不像 10+ 行。

You could do this:你可以这样做:

df <- read.table(text="x1  x2  x3
1   0   0
0   0   1
0   1   0
0   0   1", header=TRUE, stringsAsFactors=FALSE)

df <- df*col(df)
df$x4 <- rowSums(df)

  x1 x2 x3 x4
1  1  0  0  1
2  0  0  3  3
3  0  2  0  2
4  0  0  3  3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 R:如何根据单列中的唯一值组合来自多列的重复行,并通过 | 合并这些唯一值? - R: How to combine duplicated rows from multiple columns based on unique values in a single column and merge those unique values by |? R:将两列合并为具有唯一值的单列 - R: Uniting two columns into a single column with unique values R 动态合并多列 NA 为单列 - R dynamically merge multiple columns with NA into a single column 将 1 列中的多个值替换为 R 中的单个值 - Replacing multiple values in 1 column to a single value in R R按列分组,以在多个列中返回唯一值 - R Groupby by column to return unique values in multiple columns 检查 R 中多列(视为一个大“列”)中的唯一值 - Check unique values in multiple columns (treated as one big 'column') in R 在R中将多列堆叠成具有单个值的单列 - stacking multiple columns into single column with single value in R R中数据集的单列值如何除以多列值 - How to divide the values of multiple columns by the values of a single column of a dataset in R 将列值除以R中多个列的唯一数目 - Dividing a column value by unique number of multiple columns in R 根据R中的唯一值将一列数据细分为多个列 - Segmenting a column Data into multiple columns based on unique value in R
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM