[英]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.